2010/02/02

FTPの実装

javaでFTPを実装する場合、commons-netを利用することで簡単に実装することができます。
  1. public class FtpUtils {  
  2.       
  3.     /** FTPホストのIPアドレスです。 */  
  4.     private static final String HOST_ADDRESS = "192.168.0.1";  
  5.   
  6.     /** FTPユーザー名です。 */  
  7.     private static final String USER_NAME = "ftpuser";  
  8.   
  9.     /** FTPログインパスワードです。 */  
  10.     private static final String PASSWORD = "password";  
  11.   
  12.     /** FTP転送先ディレクトリ名です。 */  
  13.     private static final String STORE_DIR = "/home/ftpuser/";  
  14.   
  15.     /** 
  16.      * 指定されたファイルを順次FTP転送します。 
  17.      * 
  18.      * @param files 
  19.      *            転送対象ファイル 
  20.      * @throws IOException 
  21.      *             FTP中に何らかの例外が発生した場合 
  22.      */  
  23.     public static void storeFiles(File[] files) throws IOException {  
  24.   
  25.         FTPClient client = new FTPClient();  
  26.         InputStream in = null;  
  27.   
  28.         try {  
  29.             connection(client);  
  30.             login(client);  
  31.   
  32.             for (File file : files) {  
  33.                 in = new FileInputStream(file);  
  34.                 client.storeFile(STORE_DIR + file.getName(), in);  
  35.                 IOUtils.closeQuietly(in);  
  36.             }  
  37.   
  38.         } finally {  
  39.             IOUtils.closeQuietly(in);  
  40.             client.disconnect();  
  41.         }  
  42.     }  
  43.   
  44.     /** 
  45.      * FTPコネクションを確立します。 
  46.      * 
  47.      * @param client 
  48.      *            クライアント 
  49.      * @throws IOException 
  50.      *             コネクションに失敗した場合 
  51.      */  
  52.     private static void connection(FTPClient client) throws IOException {  
  53.         client.connect(HOST_ADDRESS);  
  54.         if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {  
  55.             throw new IOException("Connection failed.");  
  56.         }  
  57.     }  
  58.   
  59.     /** 
  60.      * FTPログインを行います。 
  61.      * 
  62.      * @param client 
  63.      *            クライアント 
  64.      * @throws IOException 
  65.      *             FTPログインに失敗した場合 
  66.      */  
  67.     private static void login(FTPClient client) throws IOException {  
  68.         if (!client.login(USER_NAME, PASSWORD)) {  
  69.             throw new IOException("Login failed.");  
  70.         }  
  71.     }  
  72. }  

上記の場合、FtpUtils#storeFiles()にFTPしたいFileオブジェクトの配列を引き渡すと、そのFileを順次転送します。

0 件のコメント:

コメントを投稿