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

Pie*_*ter 14 java ftp apache-commons

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

aar*_*ear 27

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

/**
* 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()+"'");
        }
      }
    }
  }     
}
Run Code Online (Sandbox Code Playgroud)


Ten*_*she 20

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

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