Input/Output Stream 7.
7 Input/Output Stream
I/O Stream
Java perform I/O through stream. Java i/o means input/output provided by the
java.io package.
7.1 Stream
Stream is any input source (or) output destination for data. And stream is linked to a
physical device by java i/o stream by
i/p devices like keyboard, mouse.
o/p devices like screen, printer.
Java's IO package mostly concerns itself with the reading of raw data from a source
and writing of raw data to a destination.
The below diagram illustrates the principle of a program reading data from a source
and writing it to some destination:
Source Program Designation
A program that needs to read data from some source needs an input stream or Reader.
A program that needs to write data to some destination needs an output stream or writer.
This is also illustrated in the diagram below:
Source Input Stream/ Program Output Stream/ Designation
Reader Reader
An InputStream or Reader is linked to a source of data. An OutputStream or Writer is
linked to a destination of data.
The data is received from an i/p source and the result of program is sent to an o/p
destination.
7.2 Stream Objects
Three kinds of stream objects
System.in
System.out
System.err
System.in is an InputStream which is typically connected to keyboard input of console
programs
7.2 Java Programming Paradigms
System.out is a PrintStream. System.out normally outputs the data you write to it to the
console.
System.err is a PrintStream. System.err works like System.out except it is normally only
used to output error texts.
7.3 Stream Classes
Java i/o package contains large number of stream classes, used to process all types of
data. They are two types
1) Byte Stream Class- Handling i/o operations on bytes. Two kinds of byte stream
classes
Input Stream
Output Stream
2) Character Stream Class- Manage i/o operations on character. Two kinds of
character stream classes
Reader Stream Classes
Writer Stream Classes
Java Stream Classes
Byte Stream Classes Character Stream Classes
Input Stream Input Stream Input Stream Writer
Classes Classes Classes Classes
Figure 7.1 Classification of Java stream classes.
7.3.1 Byte Stream Classes
Byte Stream Classes provide a rich environment for handling input and output by
bytes. The stream is unidirectional. They can transmit bytes in only one direction. The
byte stream classes are Input Stream Classes and Output Stream Classes.
Input Stream Classes
Input Stream Classes is an abstract class, so we cannot create instance of this
class. We must use subclasses that inherit from this class.
Input/Output Stream 7.3
Object
InputStream
SequenceInput
FileInput Stream
Stream
PipeInput ObjectInput
Stream Stream
ByteArrayInput StringBufferedInput
Stream Stream
Filterinput
Stream
PushbackInput
BufferedInput
Stream
Stream
DataInput
Stream
DataInput
Figure 7.2 Hierarchy of Input Stream Classes
7.4 Java Programming Paradigms
Methods provide by Input Stream Classes are
Data Type Method Description
int available() Returns the number of bytes that can be read (or skipped
over) from this input stream without blocking by the next
caller of a method for this input stream.
void close() Closes this input stream and releases any system
resources associated with the stream.
void mark(int readlimit) Marks the current position in this input stream.
boolean markSupported() Tests if this input stream supports the mark and reset
methods.
abstract int read() Reads the next byte of data from the input stream.
int read(byte[] b) Reads some number of bytes from the input stream and
stores them into the buffer array b.
int read(byte[] b, Reads up to len bytes of data from the input stream into
int off, int len) an array of bytes.
void reset() Repositions this stream to the position at the time the
mark method was last called on this input stream.
long skip(long n) Skips over and discards n bytes of data from this input
stream.
Table 7.1 Methods provide by Input Stream Classes
Output Stream Classes
Output Stream Classes are derived from the base class OUTPUTSTREAM. Like
InputStream, the OutputStream is an abstract class, we cannot instantiate it.
Data Method
Description
Type
void close() Closes this output stream and releases any system
resources associated with this stream.
void flush() Flushes this output stream and forces any buffered output
bytes to be written out.
void write(byte[] b Writes b.length bytes from the specified byte array to
)
this output stream.
void write(byte[] b
, int off,
Writes len bytes from the specified byte array starting at
int len) offset off to this output stream.
Input/Output Stream 7.5
abstrac write(int b)
t void Writes the specified byte to this output stream.
Table 7.2 Methods provide by Output Stream Classes
Object
OutputStream
FileOutput Stream ObjectOutput
Stream
PipeOutput Stream
ByteArrayOutputStream
Filteroutput
Stream
BufferedOutputStream DataOutputStream PushbackOutput
Stream
Dataoutput
Figure 7.3 Hierarchy of Output Stream Classes
7.3.2 Character Stream Classes
Character Streams used to read and write 16 bit Unicode character. Two kinds of
Character Stream Classes are Reader Stream Classes and Writer Stream Classes.
7.6 Java Programming Paradigms
Reader Stream Classes
Reader stream classes are used to read character from the files. Reader class is the
base class for all other classes, reader stream classes uses characters as a functional unit
of information
Object
Reader
StringReader
BufferedReader
Classe
PipeReader
CharArrayReader
InputStreamReader FilterReader
FileReader PushbackReader
Figure 7.4 Hierarchy of Reader Stream Classes
Data Type Method Description
abstract close()
void Close the stream.
void mark(int readAheadLimi
t) Mark the present position in the stream.
boolean markSupported() Tell whether this stream supports the mark()
operation.
int read() Read a single character.
Input/Output Stream 7.7
int read(char[] cbuf) Read characters into an array.
abstract read(char[] cbuf,
int int off, int len) Read characters into a portion of an array.
boolean ready() Tell whether this stream is ready to be read.
void reset() Reset the stream.
long skip(long n) Skip characters.
Table 7.3 Methods provide by Reader Stream Classes
Writer Stream Classes
Writer Stream Classes are used to perform all output operations on files. Writer
Stream Classes are designed to write characters. The writer class is an abstract class
which acts as a base class for all the other writer stream classes.
Object
Writer
PrintWriter
BufferedWriter
CharArrayWriter StringWriter
FilterWriter PipeWriter
OutputStreamWriter
FileWriter
Figure 7.5 Hierarchy of Write Stream Classes
Data Type Method Description
void close() Close the stream.
7.8 Java Programming Paradigms
void flush() Flush the stream.
String getEncoding() Return the name of the character encoding being used by
this stream.
void write(char[] c
buf, int off, Write a portion of an array of characters.
int len)
void write(int c) Write a single character.
void write(String st
r, int off, Write a portion of a string.
int len)
Table 7.4 Methods provide by Writer Stream Classes are:
Example Programs on I/O Stream:
import java.io.*;
class CharReader
{
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the characters, press . to stop reading");
do
{
c=(char)br.read();
System.out.println(c);
}
while(c != '.');
}
}
Program 7.1 To read a character
Output
D:\my book\io stream>java CharReader
Enter the characters and type . to stop reading
java.io
Input/Output Stream 7.9
j
a
v
a
.
import java.io.*;
public class StringReader
{
public static void main (String[] args)
{
System.out.println("Type some text and press 'Enter.'");
String string = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
try
{
string = reader.readLine();
}
catch(Exception e){}
System.out.println("You typed: " + string);
System.out.println("Type 'Enter' to exit.");
try
{
string = reader.readLine();
}
catch(Exception e){System.out.println(e);}
}
}
Program 7.2 To read String
Output:
D:\my book\io stream>java StringReader
Type some text and press 'Enter.'
wel come to java program.
You typed: wel come to java program.
Type 'Enter' to exit.
import java.io.*;
class CreateFile
{
7.10 Java Programming Paradigms
public static void main(String[] args) throws IOException
{
File f=new File("samplefile.txt");
if(!f.exists())
{
f.createNewFile();
System.out.println("New file \"samplefile.txt\" has been created to the current
directory");
}
}
}
Program 7.3 To create a file
Output
D:\my book\io stream>java CreateFile
New file "samplefile.txt" has been created to the current directory
import java.io.*;
class Write
{
public static void main(String args[])
{
try
{
FileOutputStream fos=new FileOutputStream("Write.txt");
String s= "welcome to java Program";
byte b[]=s.getBytes();
fos.write(b);
fos.close();
System.out.println("Successfully saved");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Program 7.4 To write a file
Input/Output Stream 7.11
Output
The string content will be saved in the file.
D:\my book\io stream>java Write
Successfully saved
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFile
{
public static void main(String[] args)
{
File file = new File("Write.txt");
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Program 7.5 To Reading a file using Scanner
Output
D:\my book\io stream>java ScannerReadFile
welcome to java Program
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
7.12 Java Programming Paradigms
FileInputStream fstream = new FileInputStream("Write.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Program 7.6 To read a file using FileInputStream
Output
D:\my book\io stream>java FileRead
welcome to java Program
Review Questions
Part-A (2 marks)
1) What is a stream and which class allows you to read objects directly from a
stream?
2) What are the methods provided by inputstream classes?
3) What are the methods provided by outputstream classes?
Part-B
1) Explain IO Stream with example programs.
2) Write a program to read a character.
3) Write a program to read a string.
4) Write a program to create a file.
5) Write a program to write the content in the file.
6) Write a program to read a file using FileInputStream.
7) Write a program to reading a file using Scanner.