使用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 Overflowicon-default.png?t=LBL2https://stackoverflow.com/questions/64692492/files-uploaded-using-apache-common-net-ftpclient-storefilestream-are-corrupted

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值