加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

记录java ftp下载图片只有96KB的问题

发布时间:2020-12-15 08:02:51 所属栏目:Java 来源:网络整理
导读:public InputStream downloadFile(String path) { if (StringUtils.isBlank(path)) { return null ; } connnect(); try { return ftpClient.retrieveFileStream(path); } catch (IOException e) { e.printStackTrace(); throw new BusinessException("ftp下
public InputStream  downloadFile(String path) {
    if(StringUtils.isBlank(path)) {
        return null;
    }
        
    connnect();
        
    try {
        return ftpClient.retrieveFileStream(path);
    } catch (IOException e) {
        e.printStackTrace();
        throw new BusinessException("ftp下载文件失败");
    }finally {
        disconnnect();
    }
}

上面的方法读取的流有问题,有时是完整的,有时是96KB,经过多次调试和查资料,优化为下面的方法

主要是标红的两句代码,先关闭输入流,再调用 completePendingCommand 方法

public byte[]  downloadFile1(String path) {
    byte[] byteArray1=new byte[0];
    if(StringUtils.isBlank(path)) {
        return null;
    }
        
    connnect();
        
    try {
        InputStream  is  =ftpClient.retrieveFileStream(path);
        ByteArrayOutputStream out=new ByteArrayOutputStream(); 
        int firstByte = -1;
        do {
            firstByte = is.read();
            int length = is.available();
            byte[] byteArray = new byte[length+1];
            byteArray[0] = (byte)firstByte;
            is.read(byteArray,1,length);
            out.write(byteArray);
        } while (firstByte>-1); 
        byteArray1= out.toByteArray();
            
        is.close();
        ftpClient.completePendingCommand();
    } catch (IOException e) {
        e.printStackTrace();
        throw new BusinessException("ftp下载文件失败");
    }finally {
        disconnnect();
    }
    return byteArray1;
}            

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读