Linux上上传跟Windows上上传不一样,在Windows上测试没问题,但是放到Linux服务器上跑,上传的文件中文显示乱码。解决方案:
FtpUtil.java红色标记处
package cn.zto.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.log4j.Logger;
import cn.zto.log4j.Log4jConfigurator;
import cn.zto.pusher.HeNanPusher;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
//import sun.net.ftp.FtpClient;
import org.apache.commons.net.ftp.*;
@SuppressWarnings({ "restriction", "unused" })
public class FtpUtil {
private Logger log = Log4jConfigurator.getLogger(FtpUtil.class);
private static String encoding = System.getProperty("file.encoding");
/**
* 本地文件名
*/
private String localfilename;
/**
* 远程文件名
*/
private String remotefilename;
/**
* FTP客户端
*/
private FTPClient ftpClient;
/**
* 服务器连接
*
* @param ip
* 服务器IP
* @param port
* 服务器端口
* @param user
* 用户名
* @param password
* 密码
* @param path
* 服务器路径
*/
public boolean connect(String hostname, int port, String username,
String password) {
ftpClient = new FTPClient();
try {
ftpClient.connect(hostname, port);
ftpClient.setControlEncoding("UTF-8");
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
if (ftpClient.login(username, password)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
this.log.debug("connect error");
return false;
}
return true;
}
/**
* 上传文件
*/
public boolean upload(String remotefilename, String xml) {
this.remotefilename = remotefilename;
try {
InputStream input = new ByteArrayInputStream(xml.getBytes("utf-8"));
ftpClient.changeWorkingDirectory(new String(remotefilename
.getBytes(encoding), "iso-8859-1"));
ftpClient.storeFile(remotefilename, input);
return true;
} catch (IOException ex) {
this.log.debug("not upload" + ex.getMessage());
return false;
}
}
}
文件内容构建处:
private static String encoding = System.getProperty("file.encoding");//获取当前系统编码,Windows跟Linux不同,这样可以自动获取处理编码
.....
// 上传到EcssCus
String remotefilename = "\\EcssCus\\" + orderNo + ".xml";
// 上传到Ciq
String remotefilename1 = "\\Ciq\\" + orderNo + ".xml";
// 上传到EcssOrders
String remotefilename2 = "\\Ciq\\Orders\\" + orderNo + ".xml";
try {
xml = new String(xml.getBytes(), encoding);
xml1 = new String(xml1.getBytes(), encoding);
xml2 = new String(xml2.getBytes(), encoding);
this.log.debug(xml);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}