从Java中的FTP服务器递归下载所有文件夹 [英] Download all folders recursively from FTP server in Java
本文介绍了从Java中的FTP服务器递归下载所有文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用我的本地目录下载(或者如果您想说同步)FTP服务器的全部内容.我已经能够下载文件并在第一层"创建目录.但是我不知道如何在其中实现子文件夹和文件.我只是无法获得工作循环.有人能帮我吗?预先感谢.
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();
}
}
我使用Apache Commons Net库.
I use the Apache Commons Net library.
推荐答案
只要找到(子)文件夹,只需将代码放入方法中并递归调用即可.可以做到:
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();
}
}
}
}
这篇关于从Java中的FTP服务器递归下载所有文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文