- public class FtpUtils {
- /** FTPホストのIPアドレスです。 */
- private static final String HOST_ADDRESS = "192.168.0.1";
- /** FTPユーザー名です。 */
- private static final String USER_NAME = "ftpuser";
- /** FTPログインパスワードです。 */
- private static final String PASSWORD = "password";
- /** FTP転送先ディレクトリ名です。 */
- private static final String STORE_DIR = "/home/ftpuser/";
- /**
- * 指定されたファイルを順次FTP転送します。
- *
- * @param files
- * 転送対象ファイル
- * @throws IOException
- * FTP中に何らかの例外が発生した場合
- */
- public static void storeFiles(File[] files) throws IOException {
- FTPClient client = new FTPClient();
- InputStream in = null;
- try {
- connection(client);
- login(client);
- for (File file : files) {
- in = new FileInputStream(file);
- client.storeFile(STORE_DIR + file.getName(), in);
- IOUtils.closeQuietly(in);
- }
- } finally {
- IOUtils.closeQuietly(in);
- client.disconnect();
- }
- }
- /**
- * FTPコネクションを確立します。
- *
- * @param client
- * クライアント
- * @throws IOException
- * コネクションに失敗した場合
- */
- private static void connection(FTPClient client) throws IOException {
- client.connect(HOST_ADDRESS);
- if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
- throw new IOException("Connection failed.");
- }
- }
- /**
- * FTPログインを行います。
- *
- * @param client
- * クライアント
- * @throws IOException
- * FTPログインに失敗した場合
- */
- private static void login(FTPClient client) throws IOException {
- if (!client.login(USER_NAME, PASSWORD)) {
- throw new IOException("Login failed.");
- }
- }
- }
上記の場合、FtpUtils#storeFiles()にFTPしたいFileオブジェクトの配列を引き渡すと、そのFileを順次転送します。
0 件のコメント:
コメントを投稿