Java是否具备在远程FTP服务器上创建文件夹层次结构的现成功能。 Apache Commons提供了一个FTP客户端,但我找不到创建目录层次结构的方法。 它确实允许创建单个目录(makeDirectory),但创建整个路径似乎并不在其中。 我想要这样做的原因是因为有时目录层次结构的一部分尚不可用,在这种情况下,我想创建层次结构的缺失部分,然后切换到新创建的目录。通过Java中的FTP创建文件夹层次结构
回答
你必须使用的FTPClient.changeWorkingDirectory
组合弄清楚,如果该目录存在,然后FTPClient.makeDirectory
如果调用FTPClient.changeWorkingDirectory
回报false
。
您需要按照上述方式在每个级别递归地遍历目录树,根据需要创建目录。
为什么不能使用FTPClient#makeDirectory()方法一次构建层次结构,一个文件夹?
阿帕奇百科全书VFS(虚拟文件系统)可以(其中包括FTP)访问多个不同的文件系统,并且还提供了createFolder方法,如果需要的话,它能够创建父目录:
http://commons.apache.org/vfs/apidocs/org/apache/commons/vfs/FileObject.html#createFolder%28%29
文档如果方法“创建该文件夹(如果该文件夹不存在),则创建任何不存在的祖先文件夹,如果该文件夹已经存在,则此方法不执行任何操作。
这可能适合您的需求。
是的,我读到了。不幸的是我不能使用这个库,因为它在目标系统上不可用。 – Pieter 2010-11-03 12:34:56
需要这个答案,所以我实现并测试了一些代码来根据需要创建目录。希望这可以帮助某人。干杯! 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()+"'");
}
}
}
}
}
使用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());
}
}
- 1. 如何在Vim中通过FTP创建文件和文件夹?
- 2. 遍历文件夹层次结构
- 3. 在Excel中通过MDX创建层次结构
- 4. Java - 通过FTP上传文件夹?
- 5. 通过FTP创建的文件不能通过FTP删除
- 6. 在SQL Server中创建层次结构
- 7. 创建文件夹/文件结构
- 8. 试图在eclipse中为Java创建单个文件,但两个在不同的文件层次结构创建
- 9. 如何检索文件夹层次结构中最后更新的文件夹?
- 10. Java树的层次结构
- 11. 获取文件夹结构层次结构的最佳数据结构?
- 12. 无法通过FTP或cPanel创建文件夹后git克隆
- 13. 文件夹层次结构中的多个位置从
- 14. 通过JavaScript显示HTML层次结构
- 15. SSAS为测量创建层次结构
- 16. BitBucket Wiki:创建一个层次结构?
- 17. 使用Linq创建层次结构
- 18. 如何创建此层次结构
- 19. java对象的层次结构,并通过对象的功能
- 20. NullReferenceException在创建文件夹结构时
- 21. 创建重复的文件夹和文件夹结构
- 22. java中的异常层次结构
- 23. eclipse中的Java项目层次结构
- 24. Java中的语言层次结构
- 25. Azure存储:任何容器下的文件夹层次结构
- 26. Java文件夹结构
- 27. VBScript:使用Excel中的文件夹结构创建文件
- 28. 创建大小超过60GB的文件夹结构树视图
- 29. Indesign脚本通过添加标签创建更深层次的结构
- 30. 循环从层次结构的不同文件夹中读取多个文件
事实上这就是我想通。基本上这是创建你自己的版本的mkdirs,但对于FTP。 – Pieter 2010-11-03 12:33:51