Chapter 4 Streams and File IO
Chapter 4 Streams and File IO
Bedasa Wayessa
Some input-output stream will be initialized automatically by the JVM and these
streams are available in System class as in, out, and err variable.
– In reference refers to the default input device, i.e. keyboard.
– Out and err refers to the default output device, i.e. console.
Java Programming CoSc3053 5
Streams
Streams are the sequence of bits(data).
There are two types of streams:
1. Input Streams
Used to read the data from various input devices like
keyboard, file, network, etc.
That provides input to a program
System.in is an input stream
2. Output Streams
used to write the data to various output devices like monitor,
file, network, etc.
That accepts output from a program
System.out is an output stream
Java Programming CoSc3053 6
Streams
Streams based on data
There are two types of streams based on data:
1. Byte Stream: used to read or write byte data.
2. Character Stream: used to read or write character data.
Reading from an Input Stream
defines the methods for the input class defines the methods for the
BufferedReader br = null;
BufferedReader br2 = null;
try{
br = new BufferedReader(new FileReader(“B:\\myfile.txt”));
String contentLine = br.readLine();
while (contentLine != null) {
System.out.println(contentLine);
contentLine = br.readLine();}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
When you compile and run the above program, it will produce
the following result:
Hello World
example
// Close the initial stream; this will close all streams connected to it.
kbd.close( );
}catch( IOException e ){
e.printStackTrace( );}
} // end of main
} // end of class definition
The result of executing main is:
Enter some characters and press return when finished: Hello World
The String was: Hello World