Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a folder hierarchy through FTP in Java

Is there readily available functionality for Java to create a folder hierarchy on a remote FTP server. Apache Commons does provide an FTP client, but I can't find a method for creating a directory hierarchy. It does allow for creating a single directory (makeDirectory), but creating an entire path does not seem to be in there. The reason I want this is because sometimes part of a directory hierarchy is not (yet) available and in such a case I want to create the missing part of the hierarchy and then change to that newly created directory.

like image 634
Pieter Avatar asked Nov 02 '10 14:11

Pieter


People also ask

What is directory in FTP?

FTP Get Default Directory is a synchronous activity that retrieves the name of the current remote directory. The default remote directory is operating system dependent and determined by the remote FTP server.

How do I find my FTP folder?

Open the Go menu and select Connect to Server or use the Command-K keyboard shortcut. In the Server Address field enter in the FTP Address (ftp://domainname.com) and select Connect. Enter the username and password into the prompt window. You can save the password and the login settings to expedite future logins.


1 Answers

Needed the answer to this and so I implemented and tested some code to create directories 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()+"'");
        }
      }
    }
  }     
}
like image 75
aaron.spear Avatar answered Sep 17 '22 08:09

aaron.spear