<p>I was surprised to find today that I couldn't track down any simple way to write the contents of an <code>InputStream</code> to an <code>OutputStream</code> in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).</p>

<p>So, given an <code>InputStream</code> <code>in</code> and an <code>OutputStream</code> <code>out</code>, is there a simpler way to write the following?</p>

<pre><code>byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
}
</code></pre>

[{'answer_id': 43163, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 7, 'selected': False, 'text': '<p>I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.</p>\n\n<pre><code>byte[] buffer = new byte[1024];\nint len;\nwhile ((len = in.read(buffer)) != -1) {\n    out.write(buffer, 0, len);\n}\n</code></pre>\n'}, {'answer_id': 43168, 'author': 'Arktronic', 'author_id': 4479, 'author_profile': 'https://Stackoverflow.com/users/4479', 'pm_score': 0, 'selected': False, 'text': '<p>PipedInputStream and PipedOutputStream may be of some use, as you can connect one to the other.</p>\n'}, {'answer_id': 43478, 'author': 'WMR', 'author_id': 2844, 'author_profile': 'https://Stackoverflow.com/users/2844', 'pm_score': 3, 'selected': False, 'text': '<p>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 <a href="http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html" rel="noreferrer">IOUtils</a> from <a href="http://commons.apache.org/io/" rel="noreferrer">Jakarta Commons IO</a>, it also has a lot of other useful things, that IMO should actually be part of the JDK...</p>\n'}, {'answer_id': 51753, 'author': 'Mikezx6r', 'author_id': 5382, 'author_profile': 'https://Stackoverflow.com/users/5382', 'pm_score': 9, 'selected': False, 'text': '<p>As WMR mentioned, <code>org.apache.commons.io.IOUtils</code> from Apache has a method called <a href="http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/IOUtils.html#copy(java.io.InputStream,%20java.io.OutputStream)" rel="noreferrer"><code>copy(InputStream,OutputStream)</code></a> which does exactly what you\'re looking for.</p>\n\n<p>So, you have:</p>\n\n<pre><code>InputStream in;\nOutputStream out;\nIOUtils.copy(in,out);\nin.close();\nout.close();\n</code></pre>\n\n<p>...in your code.</p>\n\n<p>Is there a reason you\'re avoiding <code>IOUtils</code>? </p>\n'}, {'answer_id': 540772, 'author': 'Dilum Ranatunga', 'author_id': 64967, 'author_profile': 'https://Stackoverflow.com/users/64967', 'pm_score': 4, 'selected': False, 'text': '<p><code>PipedInputStream</code> and <code>PipedOutputStream</code> should only be used when you have multiple threads, as <a href="http://docs.oracle.com/javase/8/docs/api/java/io/PipedInputStream.html" rel="noreferrer">noted by the Javadoc</a>.</p>\n\n<p>Also, note that input streams and output streams do not wrap any thread interruptions with <code>IOException</code>s... So, you should consider incorporating an interruption policy to your code:</p>\n\n<pre><code>byte[] buffer = new byte[1024];\nint len = in.read(buffer);\nwhile (len != -1) {\n    out.write(buffer, 0, len);\n    len = in.read(buffer);\n    if (Thread.interrupted()) {\n        throw new InterruptedException();\n    }\n}\n</code></pre>\n\n<p>This would be an useful addition if you expect to use this API for copying large volumes of data, or data from streams that get stuck for an intolerably long time.</p>\n'}, {'answer_id': 13814318, 'author': 'Andrew Mao', 'author_id': 586086, 'author_profile': 'https://Stackoverflow.com/users/586086', 'pm_score': 0, 'selected': False, 'text': '<p>Another possible candidate are the Guava I/O utilities:</p>\n\n<p><a href="http://code.google.com/p/guava-libraries/wiki/IOExplained" rel="nofollow">http://code.google.com/p/guava-libraries/wiki/IOExplained</a></p>\n\n<p>I thought I\'d use these since Guava is already immensely useful in my project, rather than adding yet another library for one function.</p>\n'}, {'answer_id': 18788720, 'author': 'Alexander Volkov', 'author_id': 2022586, 'author_profile': 'https://Stackoverflow.com/users/2022586', 'pm_score': 2, 'selected': False, 'text': "<p>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.</p>\n\n<pre><code>byte[] buffer = new byte[4096];\nint n;\nwhile ((n = in.read(buffer)) &gt; 0) {\n    out.write(buffer, 0, n);\n}\nout.close();\n</code></pre>\n"}, {'answer_id': 18793899, 'author': 'Jordan LaPrise', 'author_id': 2730161, 'author_profile': 'https://Stackoverflow.com/users/2730161', 'pm_score': 5, 'selected': False, 'text': '<h2>Simple Function</h2>\n\n<p>If you only need this for writing an <code>InputStream</code> to a <code>File</code> then you can use this simple function:</p>\n\n<pre><code>private void copyInputStreamToFile( InputStream in, File file ) {\n    try {\n        OutputStream out = new FileOutputStream(file);\n        byte[] buf = new byte[1024];\n        int len;\n        while((len=in.read(buf))&gt;0){\n            out.write(buf,0,len);\n        }\n        out.close();\n        in.close();\n    } catch (Exception e) {\n        e.printStackTrace();\n    }\n}\n</code></pre>\n'}, {'answer_id': 19194580, 'author': 'user1079877', 'author_id': 1079877, 'author_profile': 'https://Stackoverflow.com/users/1079877', 'pm_score': 8, 'selected': False, 'text': '<p>If you are using Java 7, <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" rel="noreferrer">Files</a> (in the standard library) is the best approach:</p>\n\n<pre><code>/* You can get Path from file also: file.toPath() */\nFiles.copy(InputStream in, Path target)\nFiles.copy(Path source, OutputStream out)\n</code></pre>\n\n<p>Edit: Of course it\'s just useful when you create one of InputStream or OutputStream from file. Use <code>file.toPath()</code> to get path from file.</p>\n\n<p>To write into an existing file (e.g. one created with <code>File.createTempFile()</code>), you\'ll need to pass the <code>REPLACE_EXISTING</code> copy option (otherwise <code>FileAlreadyExistsException</code> is thrown):</p>\n\n<pre><code>Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)\n</code></pre>\n'}, {'answer_id': 19915774, 'author': 'DejanLekic', 'author_id': 876497, 'author_profile': 'https://Stackoverflow.com/users/876497', 'pm_score': 2, 'selected': False, 'text': "<p>Use Commons Net's Util class:</p>\n\n<pre><code>import org.apache.commons.net.io.Util;\n...\nUtil.copyStream(in, out);\n</code></pre>\n"}, {'answer_id': 22223001, 'author': 'Pranav', 'author_id': 2991983, 'author_profile': 'https://Stackoverflow.com/users/2991983', 'pm_score': -1, 'selected': False, 'text': '<p>you can use this method</p>\n\n<pre><code>public static void copyStream(InputStream is, OutputStream os)\n {\n     final int buffer_size=1024;\n     try\n     {\n         byte[] bytes=new byte[buffer_size];\n         for(;;)\n         {\n           int count=is.read(bytes, 0, buffer_size);\n           if(count==-1)\n               break;\n           os.write(bytes, 0, count);\n         }\n     }\n     catch(Exception ex){}\n }\n</code></pre>\n'}, {'answer_id': 22657697, 'author': 'Andrejs', 'author_id': 1180621, 'author_profile': 'https://Stackoverflow.com/users/1180621', 'pm_score': 6, 'selected': False, 'text': '<p>Using Guava\'s <a href="https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/io/ByteStreams.html#copy-java.io.InputStream-java.io.OutputStream-" rel="noreferrer"><code>ByteStreams.copy()</code></a>:</p>\n\n<pre><code>ByteStreams.copy(inputStream, outputStream);\n</code></pre>\n'}, {'answer_id': 29420264, 'author': 'Nour Rteil', 'author_id': 4654101, 'author_profile': 'https://Stackoverflow.com/users/4654101', 'pm_score': -1, 'selected': False, 'text': '<pre><code>public static boolean copyFile(InputStream inputStream, OutputStream out) {\n    byte buf[] = new byte[1024];\n    int len;\n    long startTime=System.currentTimeMillis();\n\n    try {\n        while ((len = inputStream.read(buf)) != -1) {\n            out.write(buf, 0, len);\n        }\n\n        long endTime=System.currentTimeMillis()-startTime;\n        Log.v("","Time taken to transfer all bytes is : "+endTime);\n        out.close();\n        inputStream.close();\n\n    } catch (IOException e) {\n\n        return false;\n    }\n    return true;\n}\n</code></pre>\n'}, {'answer_id': 32136196, 'author': 'Sivakumar', 'author_id': 1879388, 'author_profile': 'https://Stackoverflow.com/users/1879388', 'pm_score': 3, 'selected': False, 'text': '<p>Using Java7 and <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="nofollow noreferrer">try-with-resources</a>, comes with a simplified and readable version.</p>\n\n<pre class="lang-java prettyprint-override"><code>try(InputStream inputStream = new FileInputStream("C:\\\\mov.mp4");\n    OutputStream outputStream = new FileOutputStream("D:\\\\mov.mp4")) {\n\n    byte[] buffer = new byte[10*1024];\n\n    for (int length; (length = inputStream.read(buffer)) != -1; ) {\n        outputStream.write(buffer, 0, length);\n    }\n} catch (FileNotFoundException exception) {\n    exception.printStackTrace();\n} catch (IOException ioException) {\n    ioException.printStackTrace();\n}\n</code></pre>\n'}, {'answer_id': 34191665, 'author': 'Bohemian', 'author_id': 256196, 'author_profile': 'https://Stackoverflow.com/users/256196', 'pm_score': 2, 'selected': False, 'text': '<p>A IMHO more minimal snippet (that also more narrowly scopes the length variable):</p>\n\n<pre><code>byte[] buffer = new byte[2048];\nfor (int n = in.read(buffer); n &gt;= 0; n = in.read(buffer))\n    out.write(buffer, 0, n);\n</code></pre>\n\n<p>As a side note, I don\'t understand why more people don\'t use a <code>for</code> loop, instead opting for a <code>while</code> with an assign-and-test expression that is regarded by some as "poor" style.</p>\n'}, {'answer_id': 39070240, 'author': 'Jin Kwon', 'author_id': 330457, 'author_profile': 'https://Stackoverflow.com/users/330457', 'pm_score': 3, 'selected': False, 'text': "<p>Here comes how I'm doing with a simplest for loop.</p>\n<pre><code>private void copy(final InputStream in, final OutputStream out)\n    throws IOException {\n    final byte[] b = new byte[8192];\n    for (int r; (r = in.read(b)) != -1;) {\n        out.write(b, 0, r);\n    }\n}\n</code></pre>\n"}, {'answer_id': 39440936, 'author': 'Ali Dehghani', 'author_id': 1393484, 'author_profile': 'https://Stackoverflow.com/users/1393484', 'pm_score': 9, 'selected': True, 'text': '<h1>Java 9</h1>\n\n<p>Since Java 9, <code>InputStream</code> provides a method called <code>transferTo</code> with the following signature:</p>\n\n<pre><code>public long transferTo(OutputStream out) throws IOException\n</code></pre>\n\n<p>As the <a href="https://docs.oracle.com/javase/9/docs/api/java/io/InputStream.html#transferTo-java.io.OutputStream-" rel="noreferrer">documentation</a> states, <code>transferTo</code> will:</p>\n\n<blockquote>\n  <p>Reads all bytes from this input stream and writes the bytes to the\n  given output stream in the order that they are read. On return, this\n  input stream will be at end of stream. This method does not close\n  either stream. </p>\n  \n  <p>This method may block indefinitely reading from the\n  input stream, or writing to the output stream. The behavior for the\n  case where the input and/or output stream is asynchronously closed, or\n  the thread interrupted during the transfer, is highly input and output\n  stream specific, and therefore not specified</p>\n</blockquote>\n\n<p>So in order to write contents of a Java <code>InputStream</code> to an <code>OutputStream</code>, you can write:</p>\n\n<pre><code>input.transferTo(output);\n</code></pre>\n'}, {'answer_id': 40019374, 'author': 'BullyWiiPlaza', 'author_id': 3764804, 'author_profile': 'https://Stackoverflow.com/users/3764804', 'pm_score': 4, 'selected': False, 'text': '<p>The <code>JDK</code> 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 <code>java.nio.file.Files.java</code>:</p>\n\n<pre class="lang-java prettyprint-override"><code>// buffer size used for reading and writing\nprivate static final int BUFFER_SIZE = 8192;\n\n/**\n  * Reads all bytes from an input stream and writes them to an output stream.\n  */\nprivate static long copy(InputStream source, OutputStream sink) throws IOException {\n    long nread = 0L;\n    byte[] buf = new byte[BUFFER_SIZE];\n    int n;\n    while ((n = source.read(buf)) &gt; 0) {\n        sink.write(buf, 0, n);\n        nread += n;\n    }\n    return nread;\n}\n</code></pre>\n'}, {'answer_id': 42004909, 'author': 'holmis83', 'author_id': 1463522, 'author_profile': 'https://Stackoverflow.com/users/1463522', 'pm_score': 4, 'selected': False, 'text': '<p>For those who use <strong>Spring framework</strong> there is a useful <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/StreamUtils.html" rel="noreferrer">StreamUtils</a> class:</p>\n\n<pre><code>StreamUtils.copy(in, out);\n</code></pre>\n\n<p>The above does not close the streams. If you want the streams closed after the copy, use <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/FileCopyUtils.html" rel="noreferrer">FileCopyUtils</a> class instead:</p>\n\n<pre><code>FileCopyUtils.copy(in, out);\n</code></pre>\n'}, {'answer_id': 46348544, 'author': 'yegor256', 'author_id': 187141, 'author_profile': 'https://Stackoverflow.com/users/187141', 'pm_score': -1, 'selected': False, 'text': '<p>Try <a href="http://www.cactoos.org" rel="nofollow noreferrer">Cactoos</a>:</p>\n\n<pre><code>new LengthOf(new TeeInput(input, output)).value();\n</code></pre>\n\n<p>More details here: <a href="http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html" rel="nofollow noreferrer">http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html</a></p>\n'}, {'answer_id': 54272980, 'author': 'Archimedes Trajano', 'author_id': 242042, 'author_profile': 'https://Stackoverflow.com/users/242042', 'pm_score': 2, 'selected': False, 'text': '<p>I use <code>BufferedInputStream</code> and <code>BufferedOutputStream</code> to remove the buffering semantics from the code</p>\n\n<pre><code>try (OutputStream out = new BufferedOutputStream(...);\n     InputStream in   = new BufferedInputStream(...))) {\n  int ch;\n  while ((ch = in.read()) != -1) {\n    out.write(ch);\n  }\n}\n</code></pre>\n'}, {'answer_id': 56980114, 'author': 'Daniel De León', 'author_id': 980442, 'author_profile': 'https://Stackoverflow.com/users/980442', 'pm_score': 2, 'selected': False, 'text': '<p><strong>This is my best shot!!</strong></p>\n\n<p><em>And do not use <code>inputStream.transferTo(...)</code> because is too generic.</em>\nYour code performance will be better if you control your buffer memory.</p>\n\n<pre><code>public static void transfer(InputStream in, OutputStream out, int buffer) throws IOException {\n    byte[] read = new byte[buffer]; // Your buffer size.\n    while (0 &lt; (buffer = in.read(read)))\n        out.write(read, 0, buffer);\n}\n</code></pre>\n\n<p>I use it with this (improvable) method when I know in advance the size of the stream.</p>\n\n<pre><code>public static void transfer(int size, InputStream in, OutputStream out) throws IOException {\n    transfer(in, out,\n            size &gt; 0xFFFF ? 0xFFFF // 16bits 65,536\n                    : size &gt; 0xFFF ? 0xFFF// 12bits 4096\n                            : size &lt; 0xFF ? 0xFF // 8bits 256\n                                    : size\n    );\n}\n</code></pre>\n'}, {'answer_id': 60788219, 'author': 'IPP Nerd', 'author_id': 4504727, 'author_profile': 'https://Stackoverflow.com/users/4504727', 'pm_score': 2, 'selected': False, 'text': '<p>Not very readable, but effective, has no dependencies and runs with any java version</p>\n<pre><code>byte[] buffer=new byte[1024];\nfor(int n; (n=inputStream.read(buffer))!=-1; outputStream.write(buffer,0,n));\n</code></pre>\n'}, {'answer_id': 68497202, 'author': 'fullmoon', 'author_id': 1143361, 'author_profile': 'https://Stackoverflow.com/users/1143361', 'pm_score': 0, 'selected': False, 'text': '<p>I used <code>ByteStreamKt.copyTo(src, dst, buffer.length)</code> method</p>\n<p>Here is my code</p>\n<pre><code>public static void replaceCurrentDb(Context context, Uri newDbUri) {\n    try {\n        File currentDb = context.getDatabasePath(DATABASE_NAME);\n        if (currentDb.exists()) {\n            InputStream src = context.getContentResolver().openInputStream(newDbUri);\n            FileOutputStream dst = new FileOutputStream(currentDb);\n            final byte[] buffer = new byte[8 * 1024];\n            ByteStreamsKt.copyTo(src, dst, buffer.length);\n            src.close();\n            dst.close();\n            Toast.makeText(context, &quot;SUCCESS! Your selected file is set as current menu.&quot;, Toast.LENGTH_LONG).show();\n        }\n        else\n            Log.e(&quot;DOWNLOAD:::: Database&quot;, &quot; fail, database not found&quot;);\n    }\n    catch (IOException e) {\n        Toast.makeText(context, &quot;Data Download FAIL.&quot;, Toast.LENGTH_LONG).show();\n        Log.e(&quot;DOWNLOAD FAIL!!!&quot;, &quot;fail, reason:&quot;, e);\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/43157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/797/']