Unit 2 I/O in Java: Structure Page Nos
Unit 2 I/O in Java: Structure Page Nos
2.0 INTRODUCTION
Input is any information that is needed by a program to complete its execution. Output
is any information that the program must convey to the user. Input and Output are
essential for applications development.
To accept input a Java program opens a stream to a data source, such as a file or
remote socket, and reads the information serially. Whether reading data from a file or
from a socket, the concept of serially reading from, and writing to, different data
sources is the same. For that very reason, it is essential to understand the features of
top-level classes (Java.io.Reader, Java.io.Writer).
In this unit you will be working on some basics of I/O (Input–Output) in Java such as
Files creation through streams in Java code. A stream is a linear, sequential flow of
bytes of input or output data. Streams are written to the file system to create files.
Streams can also be transferred over the Internet.
In this unit you will learn the basics of Java streams by reviewing the differences
between byte and character streams, and the various stream classes available in the
Java.io package. We will cover the standard process for standard Input (Reading from
console) and standard output (writing to console).
2.1 OBJECTIVES
After going through this unit you will be able to:
Streams are powerful because they abstract away the details of the communication
path from input and output operations. This allows all I/O to be performed using a
common set of methods. These methods can be extended to provide higher-level
custom I/O capabilities.
An InputStream represents a stream of data from which data can be read. Again, this
stream will be either directly connected to a device or else to another stream.
Application Fileoutputstream
File
Fileinput stream File
Java.io package
This package provides support for basic I/O operations. When you are dealing with
the Java.io package some questions given below need to be addressed.
• If you are using binary data, such as integers or doubles, then use the
InputStream and OutputStream classes.
• If you are using text data, then the Reader and Writer classes are right.
26
I/O In Java
Exceptions Handling during I/O
Almost every input or output method throws an exception. Therefore, any time you do
an I/O operation, the program needs to catch exceptions. There is a large hierarchy of
I/O exceptions derived from IOException class. Typically you can just catch
IOException, which catches all the derived class exceptions. However, some
exceptions thrown by I/O methods are not in the IOException hierarchy, so you
should be careful about exception handling during I/O operations.
A stream is a
2.3 STREAMS AND STREAM CLASSES one-way flow of
bytes from one
place to another
The Java model for I/O is entirely based on streams. over a
communication
There are two types of streams: byte streams and character streams. path.
Byte streams carry integers with values that range from 0 to 255. A diversified data
can be expressed in byte format, including numerical data, executable programs, and
byte codes – the class file that runs a Java program.
Character Streams are specialized type of byte streams that can handle only textual
data.
Most of the functionality available for byte streams is also provided for character
streams. The methods for character streams generally accept parameters of data type
char, while byte streams work with byte data types. The names of the methods in both
sets of classes are almost identical except for the suffix, that is, character-stream
classes end with the suffix Reader or Writer and byte-stream classes end with the
suffix InputStream and OutputStream.
For example, to read files using character streams use the Java.io.FileReader class,
and for reading it using byte streams use Java.io.FileInputStream.
Unless you are writing programs to work with binary data, such as image and sound
files, use readers and writers (character streams) to read and write information for the
following reasons:
• They can handle any character in the Unicode character set (while the byte
streams are limited to ISO-Latin-1 8-bit bytes).
• They are easier to internationalize because they are not dependent upon a
specific character encoding.
• They use buffering techniques internally and are therefore potentially much
more efficient than byte streams.
Now let us discuss byte stream classes and character stream classes one by one.
InputStream class
The InputStream class defines methods for reading bytes or arrays of bytes, marking
locations in the stream, skipping bytes of input, finding out the number of bytes
available for reading, and resetting the current position within the stream. An input
stream is automatically opened when created. The close() method can explicitly close
a stream. 27
Multithreading, I/O, and Methods of InputStream class
String Handling
The basic method for getting data from any InputStream object is the read()method.
public abstract int read() throws IOException: reads a single byte from the input
stream and returns it.
public int read(byte[] bytes) throws IOException: fills an array with bytes read from
the stream and returns the number of bytes read.
public int read(byte[] bytes, int offset, int length) throws IOException: fills an array
from stream starting at position offset, up to length bytes. It returns either the number
of bytes read or -1 for end of file.
public int available() throws IOException: the readmethod always blocks when there
is no data available. To avoid blocking, program might need to ask ahead of time
exactly how many bytes can safely read without blocking. The available method
returns this number.
public long skip(long n): the skip() method skips over n bytes (passed as argument of
skip()method) in a stream.
public synchronized void mark (int readLimit): this method marks the current position
in the stream so it can backed up later.
OutputStream class
The OutputStream defines methods for writing bytes or arrays of bytes to the stream.
An output stream is automatically opened when created. An Output stream can be
explicitly closed with the close() method.
public void write(byte[] bytes) throws IOException: writes the entire contents of the
bytes array to the output stream.
public void write(byte[] bytes, int offset, int length) throws IOException: writes
length number of bytes starting at position offset from the bytes array.
Now let us see how Input and Output is being handled in the program given below:
this program creates a file and writes a string in it, and reads the number of bytes in
file.
Output:
test.txt has 42 available bytes
42 bytes were read
Bytes read are: This program is for Testing I/O Operations.
Filtered Streams
One of the most powerful aspects of streams is that one stream can chain to the end of
another. For example, the basic input stream only provides a read()method for reading
bytes. If you want to read strings and integers, attach a special data input stream to an
input stream and have methods for reading strings, integers, and even floats.
The FilterInputStream and FilterOutputStream classes provide the capability to chain
streams together. The constructors for the FilterInputStream and FilterOutputStream
take InputStream and OutputStream objects as parameters:
This eliminates the need to read from the stream’s source every time an input byte is
needed.
DataInputStream class: It implements the DataInput interface, a set of methods that
allow objects and primitive data types to be read from a stream.
PushbackInputStream class: It provides the capability to push data back onto the
stream that it is read from so that it can be read again.
You can see in the program given below how objects of classes FileInputStream,
FileOutputStream, BufferedInputStream, and BufferedOutputStream are used for I/O
operations.
//program
import Java.io.*;
public class StreamsIODemo
{
public static void main(String args[])
{
try
{
int a = 1;
FileOutputStream fileout = new FileOutputStream("out.txt");
BufferedOutputStream buffout = new BufferedOutputStream(fileout);
while(a<=25)
{
buffout.write(a);
a = a+3;
}
buffout.close();
FileInputStream filein = new FileInputStream("out.txt");
BufferedInputStream buffin = new BufferedInputStream(filein);
int i=0;
do
{
i=buffin.read();
if (i!= -1)
System.out.println(" "+ i);
} while (i != -1) ;
30
I/O In Java
buffin.close();
}
catch (IOException e)
{
System.out.println("Eror Opening a file" + e);
}
}
}
Output:
1
4
7
10
13
16
19
22
25
Character Streams are defined by using two class Java.io.Reader and Java.io.Writer
hierarchies.
Both Reader and Writer are the abstract parent classes for character-stream based
classes in the Java.io package. Reader classes are used to read 16-bit character streams
and Writer classes are used to write to 16-bit character streams. The methods for
reading from and writing to streams found in these two classes and their descendant
classes (which we will discuss in the next section of this unit) given below:
int read()
int read(char cbuf[])
int read(char cbuf[], int offset, int length)
int write(int c)
int write(char cbuf[])
int write(char cbuf[], int offset, int length)
The following class hierarchy shows a few of the specialized classes in the Java.io
package:
Reader
• BufferedReader
• LineNumberReader
• FilterReader
• PushbackReader
• InputStreamReader
• FileReader
• StringReader
31
Multithreading, I/O, and Writer:
String Handling
Now let us see a program to understand how the read and write methods can be used.
import Java.io.*;
public class ReadWriteDemo
{
public static void main(String args[]) throws Exception
{
FileReader fileread = new FileReader("StrCap.Java");
PrintWriter printwrite = new PrintWriter(System.out, true);
char c[] = new char[10];
int read = 0;
while ((read = fileread.read(c)) != -1)
printwrite.write(c, 0, read);
fileread.close();
printwrite.close();
}
}
Output:
class StrCap
{
public static void main(String[] args)
{
StringBuffer StrB = new StringBuffer("Object Oriented Programming is possible in
Java");
String Hi = new String("This morning is very good");
System.out.println("Initial Capacity of StrB is :"+StrB.capacity());
System.out.println("Initial length of StrB is :"+StrB.length());
//System.out.println("value displayed by the expression Hi.capacity() is:
"+Hi.capacity());
System.out.println("value displayed by the expression Hi.length() is: "+Hi.length());
System.out.println("value displayed by the expression Hi.charAt() is:
"+Hi.charAt(10));
}
}
Note: Output of this program is the content of file StrCap.Java.You can refer unit 3 of
this block to see StrCap.Java file.
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
2) Write a program for I/O operation using BufferedInputStream and
BufferedOutputStream
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
32
I/O In Java
3) Write a program using FileReader and PrintWriter classes for file handling.
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
After this statement br is a character-based stream that is linked to the console through
Sytem.in
The program given below is for receiving console input in any of your Java
applications.
//program
import Java.io.*;
class ConsoleInput
{
static String readLine()
{
StringBuffer response = new StringBuffer();
try
33
Multithreading, I/O, and {
String Handling
BufferedInputStream buff = new BufferedInputStream(System.in);
int in = 0;
char inChar;
do
{
in = buff.read();
inChar = (char) in;
if (in != -1)
{
response.append(inChar);
}
} while ((in != 1) & (inChar != '\n'));
buff.close();
return response.toString();
}
catch (IOException e)
{
System.out.println("Exception: " + e.getMessage());
return null;
}
}
public static void main(String[] arguments)
{
System.out.print("\nWhat is your name? ");
String input = ConsoleInput.readLine();
System.out.println("\nHello, " + input);
}
}
Output:
C:\JAVA\BIN>Java ConsoleInput
What is your name? Java Tutorial
Hello, Java Tutorial
The ReadWriteDemo program discussed earlier in this section 2.3.2 of this unit is for
reading and then displaying the content of a file. This program will give you an idea
how to use FileReader and PrintWriter classes.
34