標籤:style color io os ar java 檔案 sp on
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();
}
Linux上F上傳檔案到FTP伺服器