[ACCEPTED]-Create a folder hierarchy through FTP in Java-apache-commons

Accepted answer
Score: 30

Needed the answer to this and so I implemented 2 and tested some code to create directories 1 as needed. Hope this helps someone. cheers! Aaron

/**
* utility to create an arbitrary directory hierarchy on the remote ftp server 
* @param client
* @param dirTree  the directory tree only delimited with / chars.  No file name!
* @throws Exception
*/
private static void ftpCreateDirectoryTree( FTPClient client, String dirTree ) throws IOException {

  boolean dirExists = true;

  //tokenize the string and attempt to change into each directory level.  If you cannot, then start creating.
  String[] directories = dirTree.split("/");
  for (String dir : directories ) {
    if (!dir.isEmpty() ) {
      if (dirExists) {
        dirExists = client.changeWorkingDirectory(dir);
      }
      if (!dirExists) {
        if (!client.makeDirectory(dir)) {
          throw new IOException("Unable to create remote directory '" + dir + "'.  error='" + client.getReplyString()+"'");
        }
        if (!client.changeWorkingDirectory(dir)) {
          throw new IOException("Unable to change into newly created remote directory '" + dir + "'.  error='" + client.getReplyString()+"'");
        }
      }
    }
  }     
}
Score: 21

You have to use a combination of FTPClient.changeWorkingDirectory to figure 5 out if the directory exists, then FTPClient.makeDirectory if the 4 call to FTPClient.changeWorkingDirectory returns false.

You need to recursively 3 walk the directory tree in the manner described 2 above at each level create the directory 1 as required.

Score: 2

Why can't you use the FTPClient#makeDirectory() method 2 to build the hierarchy, one folder at a 1 time?

Score: 2

Apache Commons VFS (Virtual File System) can 9 access several different filesystems (FTP 8 among them), and it also provides a createFolder 7 method that is able to create parent directories 6 if needed:

http://commons.apache.org/vfs/apidocs/org/apache/commons/vfs/FileObject.html#createFolder%28%29

Documentation states that method 5 "creates this folder, if it does not 4 exist. Also creates any ancestor folders 3 which do not exist. This method does nothing 2 if the folder already exists."

This 1 may suit your needs.

Score: 1

Use ftpSession.mkdir function to create 1 directory.

@ManagedOperation
private void ftpMakeDirectory(FtpSession ftpSession, String fullDirFilePath) throws IOException {
if (!ftpSession.exists(fullDirFilePath)) {
  String[] allPathDirectories = fullDirFilePath.split("/");
  StringBuilder partialDirPath = new StringBuilder("");
  for (String eachDir : allPathDirectories) {
    partialDirPath.append("/").append(eachDir);

    ftpSession.mkdir(partialDirPath.toString());
  }

}

More Related questions