FTPClient上传 中文目录、中文文件名乱码问题

问题描述: java

  使用org.apache.commons.net.ftp.FTPClient建立中文目录、上传中文文件名时,目录名及文件名中的中文显示为“??”。 apache

缘由: 编码

  FTP协议里面,规定文件名编码为iso-8859-1,因此目录名或文件名须要转码。 .net

解决方案: code

  将中文的目录或文件名转为iso-8859-1编码的字符。参考代码: get

   String name="目录名或文件名"; it

   name=new String(name.getBytes("GBK"),"iso-8859-1");// 转换后的目录名或文件名。 io

实例: class

public boolean upLoadFile(File file, String path, String fileName) throws IOException { boolean result = false; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(confService.getConfValue(PortalConfContants.FTP_CLIENT_HOST)); ftpClient.login(confService.getConfValue(PortalConfContants.FTP_CLIENT_USERNAME), confService .getConfValue(PortalConfContants.FTP_CLIENT_PASSWORD)); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // make directory if (path != null && !"".equals(path.trim())) { String[] pathes = path.split("/"); for (String onepath : pathes) { if (onepath == null || "".equals(onepath.trim())) { continue; } onepath=new String(onepath.getBytes("GBK"),"iso-8859-1"); if (!ftpClient.changeWorkingDirectory(onepath)) { ftpClient.makeDirectory(onepath); ftpClient.changeWorkingDirectory(onepath); } } } result = ftpClient.storeFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), new FileInputStream(file)); } catch (Exception e) { e.printStackTrace(); } finally { ftpClient.logout(); } return result; }