Easy way to write contents of a Java InputStream to an OutputStream

后端 未结 23 2442
粉色の甜心
粉色の甜心 2020-11-22 02:10

I was surprised to find today that I couldn\'t track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviou

相关标签:
23条回答
  • 2020-11-22 02:58

    Here comes how I'm doing with simplest for loop.

    private void copy(final InputStream in, final OutputStream out)
        throws IOException {
        final byte[] b = new byte[8192];
        for (int r; (r = in.read(b)) != -1;) {
            out.write(b, 0, r);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:59

    Another possible candidate are the Guava I/O utilities:

    http://code.google.com/p/guava-libraries/wiki/IOExplained

    I thought I'd use these since Guava is already immensely useful in my project, rather than adding yet another library for one function.

    0 讨论(0)
  • 2020-11-22 03:00

    Using Guava's ByteStreams.copy():

    ByteStreams.copy(inputStream, outputStream);
    
    0 讨论(0)
  • 2020-11-22 03:02

    For those who use Spring framework there is a useful StreamUtils class:

    StreamUtils.copy(in, out);
    

    The above does not close the streams. If you want the streams closed after the copy, use FileCopyUtils class instead:

    FileCopyUtils.copy(in, out);
    
    0 讨论(0)
  • 2020-11-22 03:03

    Using Java7 and try-with-resources, comes with a simplified and readable version.

    try(InputStream inputStream = new FileInputStream("C:\\mov.mp4");
        OutputStream outputStream = new FileOutputStream("D:\\mov.mp4")) {
    
        byte[] buffer = new byte[10*1024];
    
        for (int length; (length = inputStream.read(buffer)) != -1; ) {
            outputStream.write(buffer, 0, length);
        }
    } catch (FileNotFoundException exception) {
        exception.printStackTrace();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
    
    0 讨论(0)
  • 2020-11-22 03:03

    I think it's better to use a large buffer, because most of the files are greater than 1024 bytes. Also it's a good practice to check the number of read bytes to be positive.

    byte[] buffer = new byte[4096];
    int n;
    while ((n = in.read(buffer)) > 0) {
        out.write(buffer, 0, n);
    }
    out.close();
    
    0 讨论(0)
提交回复
热议问题