package com.example.demo.dao;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FtpDownload {
private static final String SERVER = "192.168.8.200";
private static final int PORT = 21;
private static final String USER = "root";
private static final String PASS = "root";
private static final String REMOTE_DIR = "/2024/06-22/17/00_49_104";
private static final String LOCAL_BASE_DIR = "C:\\Users\\tang\\Desktop\\test";
public static void main(String[] args) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(SERVER, PORT);
ftpClient.login(USER, PASS);
ftpClient.enterLocalPassiveMode(); // 使用被动模式
// 更改远程工作目录到要下载的目录
ftpClient.changeWorkingDirectory(REMOTE_DIR);
// 下载该目录下的所有文件和子目录
downloadDirectory(ftpClient, REMOTE_DIR, LOCAL_BASE_DIR);
ftpClient.logout();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static void downloadDirectory(FTPClient ftpClient, String remoteDir, String localDir) throws IOException {
FTPFile[] files = ftpClient.listFiles(remoteDir);
if (files != null && files.length > 0) {
for (FTPFile file : files) {
String remoteFilePath = remoteDir + "/" + file.getName();
String localFilePath = localDir + "/" + file.getName();
if (file.isDirectory()) {
// 创建本地目录
new java.io.File(localFilePath).mkdirs();
// 递归下载子目录
downloadDirectory(ftpClient, remoteFilePath, localFilePath);
} else {
// 下载文件
OutputStream outputStream = new FileOutputStream(new java.io.File(localFilePath));
boolean success = ftpClient.retrieveFile(remoteFilePath, outputStream);
outputStream.close();
if (success) {
System.out.println("File downloaded successfully: " + file.getName());
} else {
System.out.println("File download failed: " + file.getName());
}
}
}
}
}
}
java在FTP服务器指定下载文件
最新推荐文章于 2024-07-13 03:09:02 发布