问题
I want to download (or if you wanna say synchronize) the whole content of an FTP server with my local directory. I am already able to download the files and create the directories at the "first layer". But I don't know how to realize the subfolders and files in these. I just cant get a working loop. Can someone help me? Thanks in advance.
Here's my code so far:
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();
}
}
I use the Apache Commons Net library.
回答1:
Just put your code to a method and call it recursively, when you find a (sub)folder. This will do:
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();
}
}
}
}
回答2:
You can use FTPFile.isDirectory()
to check if current file is a directory. If it is a directory FTPClient.changeWorkingDirectory(...)
to it and continue recursively.
来源:https://stackoverflow.com/questions/50398695/download-all-folders-recursively-from-ftp-server-in-java