我想下载(或者如果你想说同步)FTP服务器的全部内容和我的本地目录。我已经能够下载文件并在"第一层"创建目录。但我不知道如何实现这些子文件夹和文件。我只是无法得到一个工作循环。有人能帮我吗?提前谢谢。
到目前为止,这是我的代码:
FTPFile[] files = ftp.listFiles();
for (FTPFile file : files){
String name = file.getName();
if(file.isFile()){
System.out.println(name);
File downloadFile = new File(pfad + name);
OutputStream os = new BufferedOutputStream(new FileOutputStream(downloadFile));
ftp.retrieveFile(name, os);
}else{
System.out.println(name);
new File(pfad + name).mkdir();
}
}
我使用Apache Commons Net库。
答案 0 :(得分:0)
您可以使用FTPFile.isDirectory()
检查当前文件是否是目录。如果它是一个目录FTPClient.changeWorkingDirectory(...)
并继续递归。
答案 1 :(得分:0)
只需将代码放入方法并在找到(子)文件夹时递归调用它。这样做:
private static void downloadFolder(
FTPClient ftpClient, String remotePath, String localPath) throws IOException
{
System.out.println("Downloading remote folder " + remotePath + " to " + localPath);
FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
for (FTPFile remoteFile : remoteFiles)
{
if (!remoteFile.getName().equals(".") && !remoteFile.getName().equals(".."))
{
String remoteFilePath = remotePath + "/" + remoteFile.getName();
String localFilePath = localPath + "/" + remoteFile.getName();
if (remoteFile.isDirectory())
{
new File(localFilePath).mkdirs();
downloadFolder(ftpClient, remoteFilePath, localFilePath);
}
else
{
System.out.println("Downloading remote file " + remoteFilePath + " to " +
localFilePath);
OutputStream outputStream =
new BufferedOutputStream(new FileOutputStream(localFilePath));
if (!ftpClient.retrieveFile(remoteFilePath, outputStream))
{
System.out.println("Failed to download file " + remoteFilePath);
}
outputStream.close();
}
}
}
}