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; }