In Java FTPClient upload Chinese directory Chinese file name garble code problem solution
- 2020-04-01 03:51:21
- OfStack
Problem description:
Using Chinese org.apache.commons.net.ftp.FTPClient create directory, upload file name, in Chinese directory name and file name in Chinese is shown as "& # 63; The & # 63;" .
The reason:
FTP protocol, the file name code is iso-8859-1, so the directory name or file name needs transcoding.
Solutions:
1. Convert the Chinese directory or file name to iso-8859-1 encoded characters. Reference code:
String name=" Directory name or file name ";
name=new String(name.getBytes("GBK"),"iso-8859-1");//The converted directory name or file name. < br / >
2. Set Linux environment variables
export LC_ALL="zh_CN.GBK"
export LANG="zh_CN.GBK"
Example:
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;
}