i

JAVA Complete Course

Byte Streams

We have already spoken about Files and some operations of files. Methods read() and write() have also another signature, which gets array of byte as a parameter. This kind of operations are faster. Generally working on bytes are faster. BufferedInputStream and BufferedOutputStream are more effective by buffering the input stream and output stream as they reduce the number of calls to the native API.

The code example below use the FileInputStream and FileOutputStream classes to perform low level binary I/O operations. This code copies one file to another, one byte at a time.

A screenshot of a cell phone

Description automatically generated

Let’s revisit the exceptions handling. In this example we see try has in parentheses InputStream and OutputStream creation. This is try with resources. Generally, while working with files, we need to close all resources after finishing work on them, but try with resources (this example) which is introduced in Java 7, helps us to deal with this automatically and take away care about resources from us.