原始发表时间: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();
}