Java是否具有随时可用的功能,可以在远程FTP服务器上创建文件夹层次结构。 Apache Commons确实提供了FTP客户端,但是我找不到创建目录层次结构的方法。
它确实允许创建单个目录(makeDirectory),但是似乎没有创建完整路径。
我之所以想要这样做,是因为有时(现在)尚无法使用目录层次结构的一部分,在这种情况下,我想创建层次结构的缺失部分,然后更改为该新创建的目录。
需要答案,因此我实现并测试了一些代码以根据需要创建目录。希望这对某人有帮助。干杯!亚伦
/**
* 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()+"'");
}
}
}
}
}
该方法是否应该不反向迭代层次结构? 如果多次调用此方法,则必须始终遍历整个树。
我确实添加了一个client.changeWorkingDirectly(" /"); 在它的末尾调用,将工作目录返回到根目录,以便随后调用该函数。
您必须使用FTPClient.changeWorkingDirectory的组合来确定目录是否存在,如果FTPClient.changeWorkingDirectory的调用返回false,则必须使用FTPClient.makeDirectory。
您需要以上述方式在每个级别上递归遍历目录树,并根据需要创建目录。
确实,这就是我所想的。 基本上,多数民众赞成在创建自己的mkdirs版本,但用于FTP。
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());
}
}