Course Content‎ > ‎Session 6‎ > ‎

File I/O in Java

Java includes a well designed collection of stream classes and interfaces that make up most of the package.

What is a stream?
In every computer program, there is exchange of data between two or more sources. Streams were created to abstract the concept of exchanging information between various devices and provide a consistent interface for programmers to interact with different sources of I/O in their programs. The basic idea of a stream is that the data enters in one end of a data channel in a particular sequence and comes out on the other end in the same sequence. Thus, streams are ordered sequences of data, which have:
  1. A source (input stream) and
  2. A destination (output stream)
File I/O in Java 
In Java, there are three streams, which are called the standard I/O streams. Besides standard I/O, Java includes a well-designed collection of stream classes and interfaces that make up most of the package. The package can be further subdivided into classes based on the data they operate on. Based on the type of the data, classes can operate on character data or the byte data.
  1. A character stream manages 16-bit Unicode characters.
  2. A byte stream manages 8-bit bytes of raw binary data. Thus, it can be used to read and write binary data such as sounds and images.
The InputStream and OutputStream classes and all their descendants represent byte streams and the Reader and Writer classes and all their descendants represent character streams.

In Java, most input-output methods can trigger an IOException (like reaching the end-of-file, file not found etc.). Such exceptions must be caught, for the proper processing of the program. These exceptions can be caught, by either using try-catch block, or the enclosing method can be flagged.