Most effective way to write File to ServletOutputStream

后端 未结 4 583
不思量自难忘°
不思量自难忘° 2020-12-14 21:19
ServletOutputStream output = response.getOutputStream();
output.write(byte[]);

What is the most effective way to write File to javax.servlet.Servle

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 21:45

    If you don't want to add that jar to your application then you have to copy it by hand. Just copy the method implementation from here: http://svn.apache.org/viewvc/commons/proper/io/trunk/src/main/java/org/apache/commons/io/IOUtils.java?revision=1004358&view=markup:

    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
    
    public static int copy(InputStream input, OutputStream output) throws IOException {
      long count = copyLarge(input, output);
      if (count > Integer.MAX_VALUE) {
        return -1;
      }
      return (int) count;
    }
    
    public static long copyLarge(InputStream input, OutputStream output)
        throws IOException {
       byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
       long count = 0;
       int n = 0;
       while (-1 != (n = input.read(buffer))) {
         output.write(buffer, 0, n);
         count += n;
       }
       return count;
    }
    

    put those 2 methods in one of your helper classes and you're good to go.

提交回复
热议问题