[ACCEPTED]-Create a folder hierarchy through FTP in Java-apache-commons
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()+"'");
}
}
}
}
}
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.
Why can't you use the FTPClient#makeDirectory() method 2 to build the hierarchy, one folder at a 1 time?
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.
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.