原始發表時間:2009-08-20
FTPClient上傳文件時,必須先關閉在服務器上打開的輸出流對象,而後再等待命令結束後登出,否則會丟失文件的最後部分。
另外,想避免亂碼,得用FTPClient 的 setControlEncoding
方法來設置編碼,不過這僅僅是針對文件內容而言,傳輸的文件名稱如果有中文的話,還是得進行轉碼。
下面黑體字
標識了這些需要注意的關鍵點相關的代碼。
參考文章
http://blog.csdn.net/wangjian5748/archive/2008/11/28/3404619.aspx
得到的最終可用的正確代碼如下:
FTPClient ftpclient = new FTPClient();
try {
listener.setProgress(TOTAL, 1, "連接 FTP...");
ftpclient.connect(...);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
listener.setProgress(TOTAL, 2, "登錄 FTP...");
ftpclient.login(...);
} catch (IOException e) {
e.printStackTrace();
}
try {
ftpclient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
ftpclient.setControlEncoding("GBK");
listener.setProgress(TOTAL, 3, "檢測 FTP 目錄...");
String
submitdatadir = ...;
ftpclient.changeWorkingDirectory(submitdatadir);
listener.setProgress(TOTAL, 4, "傳輸文件...");
OutputStream output =
ftpclient.storeFileStream(new
String(submitDataFileName.getBytes("GBK"), "iso8859-1")
);
if (output == null) {
log.debug("ReplyCode:" +
ftpclient.getReplyCode());
}
String
submitDataFileLocalPath = submitDataFileLocalDir + File.separatorChar +
submitDataFileLocalName;
InputStream input = new
FileInputStream(submitDataFileLocalPath);
int totalsize =
input.available();
log.debug("totalsize : " + totalsize);
byte[] buffer = new byte[1024];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
log.debug("count: " + count);
listener.setProgress(TOTAL, 5, "傳輸文件,已傳輸 " + (count * 100 / totalsize) + "%
...");
}
output.close();
input.close();
if
(ftpclient.completePendingCommand()) {
log.debug("logout: " +
ftpclient.logout());
ftpclient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}