2010-11-02 126 views
13

Java是否具备在远程FTP服务器上创建文件夹层次结构的现成功能。 Apache Commons提供了一个FTP客户端,但我找不到创建目录层次结构的方法。 它确实允许创建单个目录(makeDirectory),但创建整个路径似乎并不在其中。 我想要这样做的原因是因为有时目录层次结构的一部分尚不可用,在这种情况下,我想创建层次结构的缺失部分,然后切换到新创建的目录。通过Java中的FTP创建文件夹层次结构

回答

1

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

2

阿帕奇百科全书VFS(虚拟文件系统)可以(其中包括FTP)访问多个不同的文件系统,并且还提供了createFolder方法,如果需要的话,它能够创建父目录:

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

文档如果方法“创建该文件夹(如果该文件夹不存在),则创建任何不存在的祖先文件夹,如果该文件夹已经存在,则此方法不执行任何操作。

这可能适合您的需求。

+0

是的,我读到了。不幸的是我不能使用这个库,因为它在目标系统上不可用。 – Pieter 2010-11-03 12:34:56

25

需要这个答案,所以我实现并测试了一些代码来根据需要创建目录。希望这可以帮助某人。干杯! 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()+"'"); 
     } 
     } 
    } 
    }  
} 
+1

你节省了我的时间..谢谢Aaron! – Mohsin 2013-02-15 19:47:11

+0

该方法是否应该不反转层次结构?如果多次调用此方法,它必须始终遍历整个树。 – djmj 2014-07-05 01:10:36

+0

谢谢,这正是我来这么做的原因!节省时间! – Davor 2015-05-12 11:41:22

0

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

}