简体   繁体   中英

Copy all directories to server by FTP using Java

I need to copy a directory from the local disk to a server. The directory contains a lot of directories, subdirectories, and files. (Think of a hierarchy tree of directories).

Here is an example to copy one file:

 public void saveFilesToServer() throws IOException {
    FTPClient ftp = new FTPClient();
    ftp.connect(ftp.foobar.com);
    if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        ftp.disconnect();
        log.fatal("FTP not disconnected");
    }

    ftp.login("foo", "qwerty");
    log.info("Connected to server .");
    log.info(ftp.getReplyString());
    ftp.changeWorkingDirectory("test");
    ftp.makeDirectory("somedir");
    ftp.changeWorkingDirectory("somedir");
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);    
    java.io.File srcFolder = new java.io.File(folderPath);      
    FileInputStream fis = new FileInputStream(srcFolder);
    ftp.storeFile (fileName, fis);
    ftp.disconnect();
    log.info("FTP disconnected");
}

Now, I need to copy a directory ( somedir ) with all the subdirectories and files of somedir .

I think the algorithm should use recursion. Does someone know how?

The following is an example of a recursive solution to the problem:

public void saveFilesToServer(String remoteDest, File localSrc) throws IOException {
    FTPClient ftp = new FTPClient();
    ftp.connect("ftp.foobar.com");
    if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        ftp.disconnect();
        log.fatal("FTP not disconnected");
    }

    ftp.login("foo", "qwerty");
    log.info("Connected to server .");
    log.info(ftp.getReplyString());

    ftp.changeWorkingDirectory(remoteDest);
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

    try {
        upload(localSrc, ftp);
    }
    finally {
        ftp.disconnect();
        log.info("FTP disconnected");           
    }
}

public void upload(File src, FTPClient ftp) throws IOException {
    if (src.isDirectory()) {
        ftp.makeDirectory(src.getName());
        ftp.changeWorkingDirectory(src.getName());
        for (File file : src.listFiles()) {
            upload(file, ftp);
        }
        ftp.changeToParentDirectory();
    }
    else {
        InputStream srcStream = null;
        try {
            srcStream = src.toURI().toURL().openStream();
            ftp.storeFile(src.getName(), srcStream);
        }
        finally {
            IOUtils.closeQuietly(srcStream);
        }
    }
}

IOUtils is a part of Apache Commons IO .

upload(fileName){
  If (filename is not dir){
   ftpFile();
   return;
 }
 listoffiles = get the list of all files in dir 
    for each file : listoffiles {
    upload(file)
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM