在使用Apache Commom Net的FTP包上传文件时,发现如果传两个文件以上时,第一个文件传成功,但是第二个文件时,执行到
outputStream = ftpClient.storeFileStream(localFile.getName());
这行代码时,outputStrem是null,在外国一个论坛上找到比较细致的解决方案,一定要在finally里执行
ftpClient.completePendingCommand();
这段代码才行,最后贴出代码方便查阅
public void upload(File localFile, String remoteFolderPath) {
RandomAccessFile raf = null;
OutputStream outputStream = null;
try {
ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);// 二进制文件支持
ftpClient.enterLocalPassiveMode();// 使用被动模式设为默认
ftpClient.setFileTransferMode(org.apache.commons.net.ftp.FTP.STREAM_TRANSFER_MODE);// 设置模式
boolean cd = ftpClient.changeWorkingDirectory(remoteFolderPath);
// 显示进度的上传
long process = 0;
long localReadBytes = 0L;
raf = new RandomAccessFile(localFile, "r");
outputStream = ftpClient.storeFileStream(localFile.getName());
// 传输开始
byte[] bytes = new byte[1024];
int len;
while ((len = raf.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);// 写入文件
localReadBytes += len;
// 下载进度控制台显示
long nowProcess = (long) (localReadBytes * 1.0 / localFile.length() * 100);
if (nowProcess > process) {
process = nowProcess;
if (onUploadManager != null)
onUploadManager.transfering(nowProcess);
Log.i("progress", localFile.getName() + ":" + process);
}
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (raf != null) {
raf.close();
}
if (outputStream != null) {
outputStream.close();
}
ftpClient.completePendingCommand();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最后附上该论坛的地址吧: