本文主要是介绍使用Apache Common Net包上传文件FTPClient.storeFileStream二次返回null,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在使用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();}}}
最后附上该论坛的地址吧:
java - Files uploaded using Apache Common Net FTPClient.storeFileStream are corrupted - Stack Overflowhttps://stackoverflow.com/questions/64692492/files-uploaded-using-apache-common-net-ftpclient-storefilestream-are-corrupted
这篇关于使用Apache Common Net包上传文件FTPClient.storeFileStream二次返回null的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!