zoukankan      html  css  js  c++  java
  • 记录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;
    }            
  • 相关阅读:
    1245. Tree Diameter
    771. Jewels and Stones
    830. Positions of Large Groups
    648. Replace Words
    647. Palindromic Substrings
    435. Non-overlapping Intervals
    646. Maximum Length of Pair Chain
    645. Set Mismatch
    242. Valid Anagram
    438. Find All Anagrams in a String
  • 原文地址:https://www.cnblogs.com/huangzebin/p/11362526.html
Copyright © 2011-2022 走看看