BUG场景:FTP获取中文文件名乱码导致无法下载文件问题
问题描述
本机程序中使用 apache.commons.net 包中的 ftp.FTPClient 类下载文件时,由于中文命名的文件下载显示有问题。程序中使用listNames(),或者listFiles()再获取文件名,中文的文件名就会乱码。
原因分析:
FTP 传输时进行了编码处理
由于FTP Server 协议里规定文件名编码是 ISO-8859-1
解决方案:
编码处理的角度进行处理
public boolean downLoadFileForChinese(String ftpPath, String localPath, String fileName ) {
boolean isDownload=false;
try {
connect();
if(!ftpConn.changeWorkingDirectory(ftpPath)){
this.getLog().info("FTP下载FileNotFound异常,异常原因:"+ftpPath+"目录不存在!");
throw new RuntimeException("FTP下载FileNotFound异常,异常原因:"+ftpPath+"目录不存在!");
}
// 不然会有阻塞问题
ftpConn.enterLocalPassiveMode();
FTPFile[] files = ftpConn.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i]!= null) {
// 对获取的文件名进行编码转换,我这边服务端的编码是UTF-8
if (files[i].getType() == 0
&& new String(files[i].getName().getBytes("ISO-8859-1"), "UTF-8").equals(fileName)) {
File file = new File(localPath + fileName);
FileOutputStream fos = new FileOutputStream(file);
// 这里也需要对文件名进行编码转换,服务端上才能找到对应的文件
ftpConn.retrieveFile(new String(fileName.getBytes("UTF-8"), "ISO-8859-1"), fos);
if (ftpConn.getReplyCode()!=226){
logger.info(fileName+"下载失败,失败原因:"+ftpConn.getReplyString());
throw new RuntimeException(fileName+"下载失败,失败原因:"+ftpConn.getReplyString());
}
fos.close();
isDownload=true;
}
}
}
}
} catch (FileNotFoundException e) {
this.getLog().info("FTP下载FileNotFound异常,异常原因:"+fileName+e.getMessage());
throw new RuntimeException("FTP下载FileNotFound异常,异常原因:"+fileName+e.getMessage());
} catch (IOException e) {
this.getLog().info("FTP下载IO异常,异常原因:"+fileName+e.getMessage());
throw new RuntimeException("FTP下载IO异常,异常原因:"+fileName+e.getMessage());
}finally {
if (ftpConn.isConnected()){
disconnect();
}
}
return isDownload;
}
参考文章:https://blog.csdn.net/sixtyfour/article/details/9200299
https://blog.csdn.net/RenshenLi/article/details/122313833