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

后端 未结 23 2481
粉色の甜心
粉色の甜心 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 03:05

    Simple Function

    If you only need this for writing an InputStream to a File then you can use this simple function:

    private void copyInputStreamToFile( InputStream in, File file ) {
        try {
            OutputStream out = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len;
            while((len=in.read(buf))>0){
                out.write(buf,0,len);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:05

    There's no way to do this a lot easier with JDK methods, but as Apocalisp has already noted, you're not the only one with this idea: You could use IOUtils from Jakarta Commons IO, it also has a lot of other useful things, that IMO should actually be part of the JDK...

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

    A IMHO more minimal snippet (that also more narrowly scopes the length variable):

    byte[] buffer = new byte[2048];
    for (int n = in.read(buffer); n >= 0; n = in.read(buffer))
        out.write(buffer, 0, n);
    

    As a side note, I don't understand why more people don't use a for loop, instead opting for a while with an assign-and-test expression that is regarded by some as "poor" style.

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

    Use Commons Net's Util class:

    import org.apache.commons.net.io.Util;
    ...
    Util.copyStream(in, out);
    
    0 讨论(0)
  • 2020-11-22 03:07

    The JDK uses the same code so it seems like there is no "easier" way without clunky third party libraries (which probably don't do anything different anyway). The following is directly copied from java.nio.file.Files.java:

    // buffer size used for reading and writing
    private static final int BUFFER_SIZE = 8192;
    
    /**
      * Reads all bytes from an input stream and writes them to an output stream.
      */
    private static long copy(InputStream source, OutputStream sink) throws IOException {
        long nread = 0L;
        byte[] buf = new byte[BUFFER_SIZE];
        int n;
        while ((n = source.read(buf)) > 0) {
            sink.write(buf, 0, n);
            nread += n;
        }
        return nread;
    }
    
    0 讨论(0)
提交回复
热议问题