問題描述: 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; }