Unit-2 Input and Output Streams
Unit-2 Input and Output Streams
INPUT/OUTPUT BASICS
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Stream in Java
Stream in Java represents sequential flow (or unbroken flow) of data from one place to
another place.
In other words, a stream is a path along which data flows (like a pipe along which water
flows).
It is required to accept data as input from the keyboard. The data in the form of stream may
be bytes, characters, objects, etc.
Predefined Streams
The System class is defined in java.lang package. It contains three predefined stream vari-
ables: in, out, err. These are declared as public and static within the system.
• Standard Input − refers to the standard InputStream which is the keyboard by
default. This is used to feed the data to user’s program and represented as
System.in.
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
System.out.println("simple message");
System.err.println("error message");
Code1:
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
Basically, there are two types of streams in Java. They are as follows:
• Input stream
• Output stream
Input Stream:
A stream that receives or reads data from a data source and sends it to a Java program is
called input stream. Input represents the flow of data into a program.
Output Stream:
A stream that takes data from a Java program and sends or writes data to the destination
(data sink) is called output stream. A output represents the flow of data out of a program.
Output stream connects java program and a data sink. A Java program writes or sends data
to the data sink.
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Byte streams in Java are designed to provide a convenient way for handling the input and
output of bytes (i.e., units of 8-bits data). We use them for reading or writing to binary data
I/O.
Byte streams are especially used when we are working with binary files such as executable
files, image files, and files in low-level file formats such as .zip, .class, .obj, and .exe.
Binary files are those files that are machine readable. For example, a Java class file is an
extension of “.class” and humans cannot read it.
It can be processed by low-level tools such as a JVM (executable java.exe in Windows) and
java disassembler (executable javap.exe in Windows).
Another realtime example is storing a photo in a .bmp or .jpeg file. These files are certainly
not human readable. Photo editing or image manipulation software can only process them.
Byte streams that are used for reading are called input streams and for writing are
called output streams. They are represented by the abstract classes of InputStream and
OutputStream in Java.
Character Streams in Java
Character streams in Java are designed for handling the input and output of characters.
They use 16-bit Unicode characters.
Character streams are more efficient than byte streams. They are mainly used for reading or
writing to character or text-based I/O such as text files, text documents, XML, and HTML
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
files.
Text files are those files that are human readable. For example, a .txt file that contains
human-readable text. This file is created with a text editor such as Notepad in Windows.
Character streams that are used for reading are called readers and for writing are
called writers. They are represented by the abstract classes of Reader and Writer in Java
All streams in Java are represented by classes in java.io package. This package contains a
lot of stream classes that provide abilities for processing all types of data.
We can classify these stream classes into two basic groups based on the date type. They are
as follows:
• Byte Stream Classes (support for handling I/O operations based on bytes)
• Character Stream Classes (support for managing I/O operations on characters)
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an
input stream of bytes.
• The Input Strearn class is the superclass for all byte-oriented input stream classes.
• All the methods of this class throw an IOException.
• Being an abstract class, the InputStrearn class cannot be instantiated hence,
itssubclasses are used
Class Description
Contains methods to read bytes from the buffer (memory area)
BufferedInputStream
Contains methods to read bytes from a byte array
ByteArrayInputStream
Contains methods to read Java primitive data types
DataInputStream
Contains methods to read bytes from a file
FileInputStream
Contains methods to read bytes from other input streams which it
FilterInputStream
uses as its basic source of data
Contains methods to read objects
ObjectInputStream
Contains methods to read from a piped output stream. Apipe input
Piped Input Stream
stream must be connected to a piped output stream
Contains methods to concatenate multiple input streams and then read
SequenceInputStream
from the combined stream
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Method Description
public abstract int read() Reads the next byte of data from the input stream. It returns -1at
throws IOException the end of file.
public int available() Returns an estimate of the number of bytes that can be read
throws IOException from the current input stream.
public void close() Close the current input stream
throws IOException
Class Description
BufferedOutputStream Contains methods to write bytes into the buffer
ByteArrayOutputStream Contains methods to write bytes into a byte array
DataOutputStream Contains methods to write Java primitive data types
FileOutputStream Contains methods to write bytes to a file
FilterOutputStream Contains methods to write to other output streams
ObjectOutputStream Contains methods to write objects
PipedOutputStream Contains methods to write to a piped output stream
PrintStream Contains methods to print Java primitive data types
Method Description
public void write(int)throws Write a byte to the current output stream.
IOException
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Byte Stream classes in Java provide sufficient functionality to handle 1 byte (i.e. 8 bits) of any
type of I/O operation.
But it is incompatible to work directly with 16-bit Unicode characters.
To overcome this problem, Java platform added later CharacterStream classes to support for
characters.
CharacterStream classes were added in Java 1.1 version. It is not a part of language when it
was released in 1995.
Like byte stream classes, character stream classes also contain two kinds of classes. They are
named as:
• Reader Stream classes
• Writer Stream classes
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Method Description
int read() returns the integral representation of the next available char-acter
of input. It returns -1 when end of file is encountered
int read (char buffer []) attempts to read buffer. length characters into the buffer and
returns the total number of characters successfully read. It re-turns
-I when end of file is encountered
int read (char buffer [], attempts to read ‘nChars’ characters into the buffer starting at
int loc, int nChars) buffer [loc] and returns the total number of characters suc-
cessfully read. It returns -1 when end of file is encountered
long skip (long nChars) skips ‘nChars’ characters of the input stream and returns the
number of actually skipped characters
void close () closes the input source. If an attempt is made to read even
after closing the stream then it generates IOException
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Writer classes are used to write 16-bit Unicode characters onto an outputstream.
• The Writer class is the superclass for all character-oriented output stream classes .
• All the methods of this class throw an IOException.
• Being an abstract class, the Writer class cannot be instantiated hence, its subclasses
are used.
Method Description
void write () writes data to the output stream
void write (int i) Writes a single character to the output stream
void write (char buffer [] ) writes an array of characters to the output stream
void write(char buffer [],int writes ‘n’ characters from the buffer starting atbuffer [loc]
loc, int nChars) to the output stream
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
java.io.*;
class Main
{
public static void main( String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char c;
do
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
{
c = (char)br.read();
System.out.println(c);
}
while(c!=’@’);
}
}
Sample Output:
Enter characters, @ to quit
123@45
1
2
3
@
Example:
Read string from keyboard
The readLine() function with BufferedReader class’s object is used to read string from
keyboard.
Syntax:
String readLine() throws IOException
Example :
import java.io.*;
public class Main
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
}
Sample Output :
Enter your name
ims
Welcome ims
• Console output is most easily accomplished with print( ) and println( ). These methods are
defined by the class PrintStream (which is the type of object referenced by System. out).
• Since PrintStream is an output stream derived from OutputStream, it also implements the
low-level method write( ).
• So, write( ) can be used to write to the console.
Syntax:
void write(int byteval)
This method writes to the stream the byte specified by byteval.
The following java program uses write( ) to output the character “A” followed by a new-line
to the screen:
// Demonstrate System.out.write().
class WriteDemo
{
public static void main(String args[])
{
int b;
b = ‘A’;
System.out.write(b);
System.out.write(‘\n’);
}
}
THE PRINTWRITER CLASS
• Although using System.out to write to the console is acceptable, its use is recommended
mostly for debugging purposes or for sample programs.
• For real-world programs, the recommended method of writing to the console when
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
double d = 4.5e7;
pw.println(d);
}
}
Sample Output:
This is a string
-7
4.5E7
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
ii) Following constructor takes a file object to create an input stream object to read the
file. First we create a file object using File() method as follows:
File f = new File(“C:/java/hello”);
InputStream f = new FileInputStream(f);
Methods to read to stream or to do other operations on the stream.
Method Description
public void close() throws • Closes the file output stream.
IOException{} • Releases any system resources associated with the
file.
• Throws an IOException.
public int read(int r)throws • Reads the specified byte of data from the InputStream.
IOException{} • Returns an int.
• Returns the next byte of data and -1 will be returned if it’s
the end of the file.
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
public int read(byte[] r) • Reads r.length bytes from the input stream into an
throws IOException{} array.
• Returns the total number of bytes read. If it is the end of the
file, -1 will be returned.
public int available() throws • Gives the number of bytes that can be read from this file
IOException{} input stream.
• Returns an int.
There are the following steps to read data from a text file using FileInputStream that are
as follows:
1. First, we need to add a file to a FileInputStream as follows:
This FileInputStream object enables us to read data from a file in the form of bytes.
2. Next step is to read data from a file. We need to call read() method using the file input
stream object reference variable. The syntax is as follows:
chars = fis.read();
Once the read() method reads all the characters from a file, it will reach the end of the file,
and -1 will be returned if there is no more data available to read further
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
} catch(Exception e){
System.out.println(e);
}
}
}
Program code 2:
import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args)
{
try {
FileInputStream fis = new FileInputStream("D:\\myfile.txt");
// Reading all byte values from a file and display on the console.
int value = 0;
while((value = fis.read())!=-1)
{
System.out.print(value + " ");
}
fis.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args)
{
try {
FileInputStream fis = new FileInputStream("D:\\myfile.txt");
int value = 0;
while((value = fis.read())!=-1)
{
System.out.print((char)value);
}
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
fis.close();
} catch(Exception e){
System.out.println(e);
}
}
}
A program where we will see how to read a single byte, an array of bytes, and a subrange
array of bytes. We will also determine the number of available bytes remaining using
available() method and skip unwanted bytes by using skip() method.
Program code 4:
package javaProgram;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFile {
public static void main(String[ ] args) throws IOException
{
FileInputStream fis = new FileInputStream("D:\\myfile.txt");
int size = fis.available();
if (fis.read(bytearray) != n) {
System.out.println("Could not get" + n + "bytes");
}
String str = new String(bytearray, 0, n);
System.out.println(str);
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
ii) Following constructor takes a file object to create an output stream object to write the
file. First, we create a file object using File() method as follows:
File f = new File(“C:/java/hello”); OutputStream
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
f = new FileOutputStream(f);
Methods to write to stream or to do other operations on the stream
Method Descriptio
n
public void close() throws • Closes the file output stream.
IO-Exception{} • Releases any system resources associated with
the
file.
• Throws an IOException.
protected void • Cleans up the connection to the file.
finalize()throws IOException • Ensures that the close method of this file output
{} stream is called when there are no more
referencesto this stream.
• Throws an IOException.
public void write(int • Writes the specified byte to the output stream.
w)throws IOException{}
public void write(byte[] w) • Writes w.length bytes from the mentioned byte
array to the OutputStream.
There are the following steps to create a text file that will store some characters or text. They
are:
1. First, we need to read data from the keyboard. For this purpose, we will have to attach
keyboard to an input stream class. The syntax for reading data from keyboard is given
below:
DataInputStream dis = new DataInputStream(System.in);
In the above statement, System.in represents the keyboard that is linked with
DataInputStream object whose reference variable is dis.
2. Second, attach a file where data is to be stored to an output stream. For this purpose, the
syntax for attaching a file fileout.txt to FileOutputStream is given below:
3. Third step is to read data from DataInputStream and write it into FileOutputStream. This
means that we will read data from dis object and write it into fos object. The syntax is as
follows:
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
Program code 1:
package javaProgram;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args)
{
try {
// Store the filepath into the variable filepath of type String.
String filepath = "D:\\fileout.txt";
// Create an object of FileOutputStream class to attach file with FileOutputStream and pass
the filepath to its constructor.
FileOutputStream fos = new FileOutputStream(filepath);
fos.write(87);
fos.close(); // Closing file.
System.out.println("Successfully written");
}catch(FileNotFoundException e){
System.out.println(e);
}
}
}
Output:
Successfully written
Data “W” is successfully written into the text file fileout.txt.
Program code 2:
package javaProgram;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args)
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
{
try {
String filepath = "D:\\fileout.txt";
FileOutputStream fos = new FileOutputStream(filepath);
String str = "IMS Ghaziabd";
System.out.println("Successfully written");
}catch(Exception e){
System.out.println(e);
}
}
}
Output:
Successfully written
Data “IMS Ghaziabad” is successfully written into the text file fileout.txt.
An example program where we will understand how to read data from the keyboard and
write it to fileout.txt file. Look at the program source code to understand better.
Program code 3:
package javaProgram;
import java.io.DataInputStream;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args)
{
try {
// Create an object of DataInputStream to attach keyboard to DataInputStream.
DataInputStream dis = new DataInputStream(System.in);
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
int value = 0;
// Read the values (in byte form) from dis into ch and write them into fos.
while((value = dis.read()) != '@'){
char ch = (char)value; // Converting byte values into characters.
fos.write(ch);
}
Let’s create a program to copy data from one file to another file using FileInputStream
and FileOutputStream classes. In the first file myfile.txt, we will store data as “Welcome to
Scientech Easy”.
Then, we will copy it and store it in the second file myfileout.txt. Look at the source code to
understand better.
Program code 4:
package javaProgram;
import java.io.FileInputStream;
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
import java.io.FileOutputStream;
public class CopyData {
public static void main(String[] args)
{
try
{
FileInputStream fis = new FileInputStream("D:\\myfile.txt");
FileOutputStream fos = new FileOutputStream("D:\\myfileout.txt");
int i = 0;
while ((i = fis.read()) != -1){
char ch = (char)i;
fos.write(ch);
}
fis.close();
System.out.println("Successfully written...");
} catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Successfully written...
BufferedInputStream class
Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
The BufferedInputStream class, a member of the java.io package, is an implementation of a
filtered input stream that provides buffering capabilities for other input streams.
Buffering can speed up I/O operations since it reduces the need to interact directly and
frequently with the source of the data.
The important points about BufferedInputStream are:
o When the bytes from the stream are skipped or read, the internal buffer automatically
refilled from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
How it Works
By wrapping an existing input stream (like FileInputStream) with a BufferedInputStream, we can
read data from the buffer instead of the original source. This buffer gets refilled automatically when
it runs out of data, leading to fewer I/O operations and improved performance.
Program-1
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
The BufferedOutputStream class, found in the java.io package, is a filtered output stream that uses
an internal buffer to collect data before actually writing it to the underlying output stream. By
accumulating data in a buffer and then writing it in chunks, it helps reduce the I/O cost.
Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to
store data. It adds more efficiency than to write data directly into a stream. So, it makes the
performance fast.
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Java Input
Java provides different ways to get input from the user. Input from user using the object
of Scanner class. In order to use the object of Scanner, we need to import java.util.Scanner package.
import java.util.Scanner;
Then, we need to create an object of the Scanner class. We can use the object to take input from the
user.
// create an object of Scanner
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering
import java.util.Scanner;
class Input
{
public static void main(String[] args)
{
We then call the nextInt() method of the Scanner class to get an integer input from the user.
Note: We have used the close() method to close the object. It is recommended to close the scanner
object once the input is taken.
SUDHAKAR DWIVEDI-IMSEC-GZB-CSE