在Java中通过FTP创建文件夹层次结构

是否有现成的Javafunction可以在远程FTP服务器上创建文件夹层次结构。 Apache Commons确实提供了一个FTP客户端,但我找不到创建目录层次结构的方法。 它确实允许创建一个目录(makeDirectory),但是创建一个完整的路径似乎并不存在。 我想要这个的原因是因为有时目录层次结构的某些部分(尚未)可用,在这种情况下,我想创建层次结构的缺失部分,然后更改为新创建的目录。

您必须使用FTPClient.changeWorkingDirectory的组合来确定目录是否存在,然后使用FTPClient.makeDirectory如果对FTPClient.makeDirectory的调用返回false

您需要以上述方式递归遍历目录树,在每个级别根据需要创建目录。

需要答案,所以我实现并测试了一些代码来根据需要创建目录。 希望这有助于某人。 干杯! 亚伦

 /** * 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()+"'"); } } } } } 

Apache Commons VFS(虚拟文件系统)可以访问几个不同的文件系统(其中包括FTP),它还提供了一个createFolder方法,可以根据需要创建父目录:

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

文档说明方法“创建此文件夹,如果它不存在。还创建任何不存在的祖先文件夹。如果该文件夹已存在,则此方法不执行任何操作。”

这可能适合您的需求。

为什么不能使用FTPClient#makeDirectory()方法一次构建一个文件夹?

使用ftpSession.mkdir函数创建目录。

 @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()); } 

}