File Handling in Java

Why Byte Stream?

  • Programs use byte streams to perform input and output of 8-bit bytes
  • All byte stream classes are descended from InputStream and OutputStream
  • There are many byte stream classes – FileInputStream and FileOutputStream
  • They are used in much the same way; they differ mainly in the way they are constructed

When Not to Use Byte Streams?

  • Byte Stream represents a kind of low-level I/O that you should avoid
    • If the data contains character data, the best approach is to use character streams
    • There are also streams for more complicated data types
  • Byte streams should only be used for the most primitive I/O
  • All other streams are based on byte stream

Here is an example in which I will be implementing copying the contents from one file to another.

Here FileInputStream and FileOutputStream are two ByteStream classes used to read and write the bytes from a file. In I/O operations ‘input’ represents reading from the data and ‘output’ represents writing to.


The FileInputStream (File + Input + Stream) class used to represent the InputStream , means it takes input from someone and its name as a whole suggests that it takes data (Bytes) from files.

Same FileOutputStream used to write the stream data to file.

The in and out are objects of FileInputStream , FileOutputStream.

“(c = in.read()) != -1” this condition is used to find EOF(end of file) when file pointer reaches to EOF it returns -1 value. The read() method of FileInputStream class is used for reading one byte from the file.

The another method of FileOutputStream class is write() which used to writing one byte data to the file.

Above code read the bytes from one file “abc.txt” and writes that data to another file named as “xyz.txt”

It throws FileNotFoundException , if given file is not exists.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.