Copying a file using InputStream and OutputStream
suggest changeWe 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();
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents