
图1:FileZilla配置信息

图2:FileZilla连接时信息
从图2中我们可以看到原来它向服务器发送了OPTS UTF8 ON命令,来开启服务器对UTF-8的支持。所以我们也可以仿照FileZilla那样向服务器发送该命令。如果服务器支持UTF-8我们就用UTTF-8,否则我们就用本地编码(GBK)来处理中文文件名。
下面是Java代码:
/** 本地字符编码 */
private static String LOCAL_CHARSET = "GBK";// FTP协议里面,规定文件名编码为iso-8859-1private static String SERVER_CHARSET = "ISO-8859-1";private void connectFtpServer() {
if (ftpClient == null) {
ftpClient = new FTPClient();
}
if (ftpClient.isConnected()) {
return;
}
String host = getConfigValue(ADDRESS);
int port = Integer.valueOf(getConfigValue(PORT));String user = getConfigValue(USER);
String password = getConfigValue(PASSWORD);try {
ftpClient.connect(host, port);
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {if (ftpClient.login(user, password)) {
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
LOCAL_CHARSET = "UTF-8";
}
ftpClient.setControlEncoding(LOCAL_CHARSET);ftpClient.enterLocalPassiveMode();// 设置被动模式ftpClient.setFileType(getTransforModule());// 设置传输的模式return;
} else {
throw new FileStorageException(
"Connet ftpServer error! Please check user or password");}
}
} catch (IOException e) {
disConnectServer();
throw new FileStorageException(
"Connet ftpServer error! Please check the Configuration");}
}
上传文件时,文件名称需要做编码转换
fileName = new String(fileName.getBytes(LOCAL_CHARSET),SERVER_CHARSET);
通过上述方法,就能解决了中文乱码的问题。谢谢阅读,希望能帮到大家,请继续关注脚本之家,我们会努力分享更多优秀的文章。