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


    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;
    }            
  • 相关阅读:
    泛型
    多播委托
    匿名方法
    委托
    正则表达式
    压缩和解压,文件读取练习
    Vue样式绑定
    Vue跑马灯
    Vue中的v-for遍历循环
    Vue框架
  • 原文地址:https://www.cnblogs.com/huangzebin/p/11362526.html
Copyright © 2020-2023  润新知