By Matt Sheppard


2008-09-04 03:46:16 8 Comments

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. 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).

So, given an InputStream in and an OutputStream out, is there a simpler way to write the following?

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

22 comments

@Daniel De León 2019-07-11 00:13:01

This is my best shot!!

And do not use inputStream.transferTo(...) because is too generic. Your code performance will be better if you control your buffer memory.

public static void transfer(InputStream in, OutputStream out, int buffer) throws IOException {
    byte[] read = new byte[buffer]; // Your buffer size.
    while (0 < (buffer = in.read(read)))
        out.write(read, 0, buffer);
}

I use it with this (improvable) method when I know in advance the size of the stream.

public static void transfer(int size, InputStream in, OutputStream out) throws IOException {
    transfer(in, out,
            size > 0xFFFF ? 0xFFFF // 16bits 65,536
                    : size > 0xFFF ? 0xFFF// 12bits 4096
                            : size < 0xFF ? 0xFF // 8bits 256
                                    : size
    );
}

@Archimedes Trajano 2019-01-20 02:04:10

I use BufferedInputStream and BufferedOutputStream to remove the buffering semantics from the code

try (OutputStream out = new BufferedOutputStream(...);
     InputStream in   = new BufferedInputStream(...))) {
  int ch;
  while ((ch = in.read()) != -1) {
    out.write(ch);
  }
}

@Andrejs 2014-03-26 10:12:22

Using Guava's ByteStreams.copy():

ByteStreams.copy(inputStream, outputStream);

@WonderCsabo 2014-11-08 08:40:15

Do not forget to close the streams after that!

@Hong 2018-03-29 16:32:19

This is the best answer if you are already using Guava which has become indispensable for me.

@ZhekaKozlov 2018-06-07 07:38:26

@Hong You should use Files.copy as much as possible. Use ByteStreams.copy only if both of streams are not FileInputStream/FileOutputStream.

@Hong 2018-06-07 11:38:27

@ZhekaKozlov Thank you for the tip. In my case, the input stream is from an Android app's resource (drawable).

@Ali Dehghani 2016-09-11 21:44:31

Java 9

Since Java 9, InputStream provides a method called transferTo with the following signature:

public long transferTo(OutputStream out) throws IOException

As the documentation states, transferTo will:

Reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read. On return, this input stream will be at end of stream. This method does not close either stream.

This method may block indefinitely reading from the input stream, or writing to the output stream. The behavior for the case where the input and/or output stream is asynchronously closed, or the thread interrupted during the transfer, is highly input and output stream specific, and therefore not specified

So in order to write contents of a Java InputStream to an OutputStream, you can write:

input.transferTo(output);

@ruX 2016-12-03 11:45:13

good to know for further versions

@ZhekaKozlov 2018-06-07 07:47:21

You should preferFiles.copy as much as possible. It is implemented in native code and therefore can be faster. transferTo should be used only if both streams are not FileInputStream/FileOutputStream.

@yegor256 2017-09-21 16:06:09

Try Cactoos:

new LengthOf(new TeeInput(input, output)).value();

More details here: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html

@holmis83 2017-02-02 14:33:08

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

@BullyWiiPlaza 2016-10-13 11:10:11

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

@Dragas 2018-09-13 06:56:44

Aye. Shame this particular call is private and there's no other option but to copy it out into your own utilities class, since it's possible that you're not dealing with files, but rather 2 sockets at once.

@Jin Kwon 2016-08-22 01:17:50

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

@Sivakumar 2015-08-21 08:52:19

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

@user207421 2016-02-25 00:10:57

Flushing inside the loop is highly counter-productive.

@Sivakumar 2016-07-29 11:46:00

@EJP Thanks for the hint, updated the answer.

@Bohemian 2015-12-10 00:29:32

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.

@Brian de Alwis 2016-02-08 03:15:48

Your suggestion causes a 0-byte write on the first iteration. Perhaps least do: for(int n = 0; (n = in.read(buffer)) > 0;) { out.write(buffer, 0, n); }

@Bohemian 2016-02-08 04:29:37

@BriandeAlwis You are right about the first iteration being incorrect. The code has been fixed (IMHO in a cleaner way than your suggestion) - see edited code. Thx for caring.

@user1079877 2013-10-05 06:03:45

If you are using Java 7, Files (in the standard library) is the best approach:

/* You can get Path from file also: file.toPath() */
Files.copy(InputStream in, Path target)
Files.copy(Path source, OutputStream out)

Edit: Of course it's just useful when you create one of InputStream or OutputStream from file. Use file.toPath() to get path from file.

To write into an existing file (e.g. one created with File.createTempFile()), you'll need to pass the REPLACE_EXISTING copy option (otherwise FileAlreadyExistsException is thrown):

Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)

@Matt Sheppard 2013-10-07 13:15:47

I don't think this actually solves the problem since one end is a path. While you can get a path for a file, as far as I am aware you can't get one for any generic stream (e.g. one over the network).

@Erik Allik 2014-04-09 00:29:13

+1 still turned out to be useful in my case though, as I have a real file on the output side!

@Xtreme Biker 2014-07-05 13:11:47

As far as I'm concerned, te first method you say is not available with that signature. You have to add the CopyOptions parameter.

@user1079877 2014-07-07 02:15:58

CopyOptions is arbitrary! You can put it here if you want it.

@Don Cheadle 2014-12-17 19:58:32

now this is what I was looking for! JDK to the rescue, no need for another library

@Joshua Pinter 2015-01-24 22:25:48

FYI, Files is NOT available in Android's Java 1.7. I got stung by this: stackoverflow.com/questions/24869323/…

@Ti Strga 2015-09-09 17:04:59

Amusingly, the JDK also has a Files.copy() which takes two streams, and is what all the other Files.copy() functions forward to in order to do the actual work of copying. However, it's private (since it doesn't actually involve Paths or Files at that stage), and looks exactly like the code in the OP's own question (plus a return statement). No opening, no closing, just a copy loop.

@Stuart Marks 2019-01-16 05:40:28

For Java 9 and later, use InputStream.transferTo(OutputStream). stackoverflow.com/a/39440936/1441122

@mochadwi 2019-02-23 16:49:11

Files.copy doesn't have backward support for API below 26 @user1079877

@Dilum Ranatunga 2009-02-12 10:37:28

PipedInputStream and PipedOutputStream should only be used when you have multiple threads, as noted by the Javadoc.

Also, note that input streams and output streams do not wrap any thread interruptions with IOExceptions... So, you should consider incorporating an interruption policy to your code:

byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }
}

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.

@Nour Rteil 2015-04-02 18:48:24

public static boolean copyFile(InputStream inputStream, OutputStream out) {
    byte buf[] = new byte[1024];
    int len;
    long startTime=System.currentTimeMillis();

    try {
        while ((len = inputStream.read(buf)) != -1) {
            out.write(buf, 0, len);
        }

        long endTime=System.currentTimeMillis()-startTime;
        Log.v("","Time taken to transfer all bytes is : "+endTime);
        out.close();
        inputStream.close();

    } catch (IOException e) {

        return false;
    }
    return true;
}

@rfornal 2015-04-02 19:13:50

Can you please explain why this is the right answer?

@Jordan LaPrise 2013-09-13 19:33:32

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

@Joshua Pinter 2015-01-24 23:11:41

Great function, thanks. Would you need to put the close() calls in finally blocks, though?

@Jordan LaPrise 2015-01-26 04:51:42

@JoshPinter It wouldn't hurt.

@Cel Skeggs 2015-12-12 20:40:03

You probably should both include a finally block and not swallow exceptions in an actual implementation. Also, closing an InputStream passed to a method is sometimes unexpected by the calling method, so one should consider if it's the behavior they want.

@Prabhakar 2017-01-13 19:13:39

Why catch the Exception when IOException suffices?

@Mikezx6r 2008-09-09 12:36:43

As WMR mentioned, org.apache.commons.io.IOUtils from Apache has a method called copy(InputStream,OutputStream) which does exactly what you're looking for.

So, you have:

InputStream in;
OutputStream out;
IOUtils.copy(in,out);
in.close();
out.close();

...in your code.

Is there a reason you're avoiding IOUtils?

@Jeremy Logan 2013-08-29 15:42:56

I'm avoiding it for this mobile app I'm building cause it'd quintuple the size of the app to save a measly 5 lines of code.

@basZero 2013-10-04 09:51:15

it's maybe worth to mention that in and out must be closed at the end of the code in a finally block

@Warren Dew 2014-05-17 06:31:04

@basZero Or using a try with resources block.

@MikeM 2014-06-23 07:48:28

Or you could just write your own copy(in, out) wrapper ... (in less time to takes to ...)

@Eduardo Dennis 2014-07-07 18:56:42

it was removed ??

@Jim Tough 2014-09-19 12:40:24

If you're already using the Guava library, Andrejs has recommended the ByteStreams class below. Similar to what IOUtils does, but avoids adding Commons IO to your project.

@Jigar Shah 2015-04-06 14:33:06

@Mikezx6r Above code with IOUtils, will load whole out stream in memory and then start writing to out. This in memory operation wont cause issue if large streams ?

@Olaf Dietsche 2015-05-25 21:39:32

@JigarShah Do you have a reference for that claim? When I look at the source code, I see almost the same copy loop as is shown by the OP and answers.

@Sled 2015-07-23 15:01:24

@fiXedd You can use Maven Shade to strip unneeded classes from the final .jar, thus incurring only a modest increase in file jar size

@Maarten Bodewes 2016-03-10 20:12:57

Kind of obvious, but if the class doesn't have too many dependencies, you can also simply copy the source code for liberal licenses (like those used for both Guava and Apache). First read the license though (disclaimer, IANAL etc.).

@Neeraj 2016-06-20 10:51:04

App size can be kept in control if proguard is used.

@user3792852 2016-07-25 17:25:23

If you are using a dependency manager, like Maven, and you're avoiding IOUtils and Guava for size reasons, you might want to have a look at your dependency hierarchy. Maybe one of your dependencies transitively includes one of these without notice, they are very famous after all. If that's the case, you might as well use them yourself , you're including them anyway.

@Pranav 2014-03-06 11:23:20

you can use this method

public static void copyStream(InputStream is, OutputStream os)
 {
     final int buffer_size=1024;
     try
     {
         byte[] bytes=new byte[buffer_size];
         for(;;)
         {
           int count=is.read(bytes, 0, buffer_size);
           if(count==-1)
               break;
           os.write(bytes, 0, count);
         }
     }
     catch(Exception ex){}
 }

@UnclickableCharacter 2017-07-25 14:41:26

catch(Exception ex){} — this is top-notch

@DejanLekic 2013-11-11 20:56:35

Use Commons Net's Util class:

import org.apache.commons.net.io.Util;
...
Util.copyStream(in, out);

@Alexander Volkov 2013-09-13 14:24:37

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();

@user207421 2013-10-30 08:06:18

Using a large buffer is indeed a good idea but not because files are mostly > 1k, it is to amortize the cost of system calls.

@Andrew Mao 2012-12-11 05:42:34

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.

@Raekye 2013-08-06 16:21:33

There are copy and toByteArray methods in docs.guava-libraries.googlecode.com/git-history/release/java‌​doc/… (guava calls input/output streams as "byte streams" and readers/writers as "char streams")

@rupps 2014-11-28 00:08:10

if you already use guava libraries it's a good idea, but if not, they are a mammoth library with thousands of methods 'google-way-of-doing-everything-different-to-the-standard'. I'd keep away from them

@WMR 2008-09-04 10:50:10

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...

@Arktronic 2008-09-04 04:04:07

PipedInputStream and PipedOutputStream may be of some use, as you can connect one to the other.

@Raekye 2013-08-06 16:20:27

This is not good for single-threaded code as it could deadlock; see this question stackoverflow.com/questions/484119/…

@user207421 2013-10-30 08:05:06

May be of some use how? He already has an input stream and an output stream. How will adding another one of each help exactly?

@Mike Stone 2008-09-04 03:58:20

I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.

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

@Aaron Digulla 2008-12-13 09:24:39

I suggest a buffer of at least 10KB to 100KB. That's not much and can speed up copying large amounts of data tremendously.

@Kevin Parker 2011-09-09 18:28:41

This did the trick for me when writing a file. I did not realize I needed to get the actual length readd from the input stream and use that to output to a file.

@phil294 2015-01-02 14:26:17

you might want to say while(len > 0) instead of != -1, because the latter could also return 0 when using the read(byte b[], int off, int len)-method, which throws an exception @ out.write

@Christoffer Hammarström 2015-05-06 16:37:58

@Blauhirn: That would be incorrect, as it is entirely legal according to the InputStream contract for read to return 0 any number of times. And according to the OutputStream contract, the write method must accept a length of 0, and should only throw an exception when len is negative.

@ɲeuroburɳ 2015-07-24 17:19:28

You can save a line by changing the while to a for and putting one of the variables in for's init section: e.g., for (int n ; (n = in.read(buf)) != -1 ;) out.write(buf, 0, n);. =)

@user207421 2016-02-25 00:09:48

@Blauhim read() can only return zero if you supplied a length of zero, which would be a programming error, and a stupid condition to loop forever on. And write() does not throw an exception if you provide a zero length.

@Andreas 2016-12-16 05:47:36

@ChristofferHammarström It is not legal for InputStream.read(byte[] b) to return 0 (unless you're stupid like EJP said): If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

@Christoffer Hammarström 2016-12-16 15:16:12

@Andreas: Thanks! I never realized. I could imagine use cases though where you'd want to pass a zero length buffer, or when it happens for other reasons. So just like i always wear my seat belt, i will still always check for -1. Stopping reading and discarding remaining data is at least as much an error as passing an empty buffer.

@user207421 2017-06-18 03:15:43

There is no other reason:only a zero-length buffer or a zero length parameter. The meaning of your final sentence escapes me.

Related Questions

Sponsored Content

33 Answered Questions

[SOLVED] What's the simplest way to print a Java array?

  • 2009-01-03 20:39:39
  • Alex Spurling
  • 2127283 View
  • 1826 Score
  • 33 Answer
  • Tags:   java arrays printing

29 Answered Questions

[SOLVED] What is an efficient way to implement a singleton pattern in Java?

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

30 Answered Questions

[SOLVED] How do I create a file and write to it in Java?

  • 2010-05-21 19:58:55
  • Drew Johnson
  • 2758804 View
  • 1320 Score
  • 30 Answer
  • Tags:   java file-io

31 Answered Questions

[SOLVED] Convert InputStream to byte array in Java

32 Answered Questions

[SOLVED] How do I create a Java string from the contents of a file?

12 Answered Questions

[SOLVED] How to convert OutputStream to InputStream?

3 Answered Questions

[SOLVED] How do I convert a String to an InputStream in Java?

5 Answered Questions

[SOLVED] Most efficient way to create InputStream from OutputStream

4 Answered Questions

[SOLVED] How does BufferedOutputStream actually work at a low level?

Sponsored Content