FTP获取中文文件名乱码导致无法下载文件问题

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值