We can directly copy data from a source to a data sink using a loop. In this example, we are reading data from an InputStream and at the same time, writing to an OutputStream. Once we are done reading and writing, we have to close the resource.
public void copy(InputStream source, OutputStream destination) throws IOException {
try {
int c;
while ((c = source.read()) != -1) {
destination.write(c);
}
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}