JavaによるFTP転送サンプル

仕事で、JavaによるFTPのファイル転送をすることになり、簡単なサンプルを作りました。

PASVモードでの転送を行うため、「Apache Commons Net」を利用させてもらいました。

接続の確認やディレクトリ/ファイルの取得のサンプルはいくつか見つけたのですが、リモートのディレクトリを再帰的に取得したり、コマンドを発行するサンプルはあまり無かったので、備忘録的に上げておきたいと思います。

package jp.koji.batch;
 
import java.io.IOException;
import java.io.FileOutputStream;
 
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPFile;
 
public class FTPTest {
 
    private static final String hostname = "localhost";
    private static final int portno = 21;
    private static final String username = "XXXXXX";
    private static final String password = "XXXXXX";
 
    private static final String localRootFolder = "c:/tmp";
 
    //Binary転送Modeを利用?(true=Yes、false=No)
    private static final boolean binaryTransfer = false;
 
    //PASV Modeを利用?(true=Yes、false=No)
    private static final boolean usePassiveMode = true;
 
 
    public static void main(String[] arg) throws Exception {
 
 
        execute(hostname, username, password, usePassiveMode);
 
    }
 
    private static boolean execute(String address, String username,
            String password, boolean usePassiveMode) throws IOException{
        boolean success = false;
        FTPClient client = new FTPClient();
        try {
            System.out.println("connect....");
            client.setControlEncoding("MS932");
            client.connect(address, portno);
            System.out.println("Connected to Server:" + address + " on "+client.getRemotePort());
 
            System.out.println(client.getReplyString());
 
            client.login(username, password);
            System.out.println(client.getReplyString());
            if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
 
                System.out.println("Login Failed");
                client.disconnect();
                return false;
            }
 
            if (binaryTransfer){
                client.setFileType(FTP.BINARY_FILE_TYPE);
                System.out.println("Mode binaryTransfer = true");
            }
 
            if (usePassiveMode) {
                client.enterLocalPassiveMode();
                System.out.println("Mode usePassiveMode = ON");
            } else {
                client.enterLocalActiveMode();
                System.out.println("Mode usePassiveMode = OFF");
            }
 
            String fileNames[] = client.listNames();
            System.out.println(client.getReplyString());
            success = FTPReply.isPositiveCompletion(client.getReplyCode());
 
            System.out.println("Connection test => " + (success ? "OK" : "NG"));
 
            if (fileNames != null) {
                for (int i = 0; i < fileNames.length; i++) {
                    System.out.println("Name=" +fileNames[i]);
                }
            }
 
 
            System.out.println("-----------------------------------");
            for (FTPFile f : client.listFiles()) {
                getRemoteFiles(f, client);
            }
 
 
 
            client.logout();
            System.out.println(client.getReplyString());
 
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (client.isConnected()) client.disconnect();
 
        }
        return success;
    }
 
 
    private static void getRemoteFiles(FTPFile file, FTPClient client)throws Exception{
 
        if (!file.getName().equals(".")&&!file.getName().equals("..")) {
 
            String currentDir = client.printWorkingDirectory();
            if(file.isFile()){
                //If File
                String filename = client.printWorkingDirectory()+ (currentDir.endsWith("/") ? "" : "/")+file.getName();
                filename = new String(filename.getBytes("MS932"), "UTF-8");
 
                String utf8filename = client.printWorkingDirectory()+ (currentDir.endsWith("/") ? "" : "/")+file.getName();
 
                System.out.println("FileName="+utf8filename);
                System.out.println(new String(file.getName().getBytes("MS932"), "UTF-8"));
 
                //FILE GET
                FileOutputStream os = null;
                try{
                    //File SEND
                    os = new FileOutputStream(localRootFolder + filename);
                    client.retrieveFile(utf8filename, os);
                    os.close();
                    System.out.println("FTP GET COMPLETED");
 
                }catch(Exception ex){
 
 
                }
 
                return;
            }else if(file.isDirectory()){
                //If Directory
                client.doCommand("CWD", client.printWorkingDirectory()+ (currentDir.endsWith("/") ? "" : "/")+file.getName());
                for (FTPFile f : client.listFiles()) {
                    getRemoteFiles(f, client);
                }
                client.doCommand("CDUP", "");
 
                return;
            }else{
                //No Action
            }
 
        }else{
 
            return;
        }
 
 
 
    }
}