Learn how to work with Streams using Java

Files are storage spaces where information and data’s are kept. Without files we cannot do even the simplest of tasks in our day to day computing life. Every programming language have the capability to access these files in some or other way.

Accessing files means reading from a file and writing to a file. We can perform these tasks via Java programming or in other words you can store user’s data in a file and can be retrieved later by way of searching, navigation etc.

Java handles the concept of files by using Streams. Technically speaking, stream is a path traveled by data in a program. When we read information from a floppy disk, there is a path for the same with which it is able to read. Same is the case of writing. But these readings and writings are invisible to either the programmer or the user.

We can classify Streams into two types of classes, viz; InputStream and OutputStream. InputStream is used for reading information from a file while OutputStream is used to write information to a file. Both these classes are abstract meaning you cannot create an object of that class. Each of these classes have several subclasses which you have to use for reading and writing.

InputStream and OutputStream classes contains lot of constructors and methods for performing various tasks. For example, to read data from a file we use read() method while to write data a file we use write() method. You have to follow the following basic steps to perform reading and writing operations.

(1) Import java.io package.
(2) Create an object of corresponding stream class by using the appropriate constructor.
(3) Apply read() or write() method properly.
(4) Finally, close the stream by calling close() method.

We can accept keyboard input in Java using predefined stream System.in. Other than this stream, Java provides us with System.out and System.err Streams. These Streams are declared in java.lang package. The programs shown below shows you how to accept inputs via keyboard, perform mathematical calculations etc.

Accepting Inputs from keyboard

  1: class Keys {
  2: public static void main(String args[]) {
  3: int x = System.in.read();
  4: System.out.println(x); 
  5: } 
  6: } 


Performing Arithmetical calculations

  1: class Calc {
  2: public static void main(String args[]) {

3: System.out.println("Enter First value");

// first value accepted

  4: int a = System.in.read();

5: System.out.println("Enter Second value");

// Second value accepted

6: int b = System.in.read();

// Sum calculated by using parseInt() of Integer class

  7: int c = Integer.parseInt(a) + Integer.parseInt(b);
  8: System.out.println("The sum is" +c);
  9: } 
 10: } 

Leave a Comment