Copying a file using InputStream and OutputStream

suggest change

We can copy data from a source to a sink one byte at a time. In this example, we read from an InputStream and write each byte to an OutputStream. Both streams are closed afterward. Closing the source in its own finally block still closes the destination if source.close() throws.

public void copy(InputStream source, OutputStream destination) throws IOException {
  try {
      int c;
      while ((c = source.read()) != -1) {
          destination.write(c);
      }
  } finally {
      if (source != null) {
          try {
              source.close();
          } finally {
              if (destination != null) {
                  destination.close();
              }
          }
      } else if (destination != null) {
          destination.close();
      }
  }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents