Java Input/Output  « Prev 

Program that uses FileInputStream and InputStreamReader to read in a File

Example of DataInputStream

To create a DataInputStream instance tied to the standard input, you can write:
DataInputStream stream = new DataInputStream(System.in);

Then, you can use the DataInputStream methods, such as readInt(), which reads 4 bytes and assembles them into an int value. In Java 1.1, reading character-based data is handled by subclasses of Reader class. To read text a line at a time, the recommended method is the readLine() method of BufferedReader class. The bridge between InputStream and BufferedReader is InputStreamReader:

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();

This way you will have read the entire line entered by the user--all in one shot. (Remember, to wrap the readLine() call in a try/catch block in case it throws an IOException.)
You will see another example of BufferedReader when we discuss the net package, coming up in the next module.

Program that uses FileInputStream and InputStreamReader to read in a File

The following program will read in the text file and at location c:\\input.txt and write it out to the console.
  1. Declare an object of type FileInputStream "inputStream" that contains the location of the input file.
  2. Chain that object with InputStreamReader

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class InputStreamReaderDemo {
 public static void main(String[] args) throws IOException {
  InputStream inputStream = new FileInputStream("c:\\input.txt");
  Reader reader = new InputStreamReader(inputStream);
  int data = 0;
  try {
   data = reader.read();
  }catch (IOException e) {
    e.printStackTrace();
  }
  while (data != -1) {
  char charInput = (char) data;
  try {
   data = reader.read();
   System.out.print(charInput); // this prints numbers
  }catch (IOException e) {
   e.printStackTrace();
  }
 }
 reader.close();
 }
}