1、前言
项目需使用ftp下载服务器上的文件
2、使用
pom
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
代码
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
public class FTPTest {
private static String username = "ftpuser";
private static String password = "123456";
private static String ip = "192.168.1.19";
private static Integer port = 21;
public static void start() {
String saveDir = "F:/Program/FTP_Save";
//下载远程文件夹下的 中文 文件
String remoteFileName = "/1/津巴多普通心理学.pdf";
String fileName = "津巴多普通心理学.pdf";
// remoteFileName = "/1/2/654321.pcm";
// fileName = "654321.pcm";
downloadFtpFile(remoteFileName, saveDir, fileName);
}
public static void downloadFtpFile(String remoteFileName, String saveDir, String fileName) {
FTPClient ftpClient = new FTPClient();
int reply;
try {
ftpClient.connect(ip, port);
ftpClient.login(username, password);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return;
}
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
File localFile = new File(saveDir + File.separatorChar + fileName);
OutputStream os = new FileOutputStream(localFile);
//ftp中文名需要iso-8859-1字符
boolean flag2 = ftpClient.retrieveFile(new String(remoteFileName.getBytes("GBK"), "iso-8859-1"), os);
if (!flag2) {
System.out.println("没有找到" + remoteFileName + "---该文件");
localFile.delete();
} else {
System.out.println("=================== save success");
}
os.close();
ftpClient.logout();
ftpClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、参考
解决FTPClient上传下载中文文件名或路径与FTPClient下载成功文件0KB问题