Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Input/Output in Java

~
Introduction
1
tS, A computer user need a bas1c. app1·1cat1on
.
to write data to the. standard output device
or any other source like file, network connection and read from the standard input or
anY other source like file, network connection. For providing read and write facilities
in the Java application, Java introduced the 1/0 Streams.

In Java, we deal with different kinds of data, e.g. bytes, primitive data types, object
etc. So Java streams support most of these types of data to read and write.

Programmer does not bothered about how they are working internally, only he/she
has to use the corresponding stream and call the methods. To read the data from
any resource input stream is used, and to write the data on any resource output

stream is used.

18.2 1/0 Basic


The purpose of a program is to enable communications between the user and the
computer. The software developed is used for carrying out desired tasks. It takes
input data from the user. The software performs specified tasks using the data
supplied. For example, In a departmental stores, the sales person enters the code
and number of items sold as the input data through the keyboard. The software
makes a bill and displays it in the monitor and prints it out. The external interface is
th
eretore essential for any Information Technology product.

[ 453]
Input refers to flow of data into a program and output means the flow of d
atao
program. Input to a program may come from the keyboard, the mouse th lJto1~
, e flle
the disk or a network. Similarly, output from a program may go to the s
ere l'l'1orv,
printer, the memory, the disk or a network etc. as shown in figure 1a. 1. en, the

Sources Destinations
Keyboard Screen

Mouse Printer

Java Program
Memory or Memory
Application

Disk Output Disk

FIGURE 18.1

Therefore, 1/0 is the mechanism provided by the Java language, which facilitates
the programmer to write an application to give 1/0 support to 1/0 devices as well as
files and networks.

18.3 Streams and Stream Classes


Java performs 1/0 through Streams. A stream can be defined as a sequence of
data.

A stream is a flowing sequences of characters.

(i) A program can get input by reading characters from a stream attached to a
data source.
h8 dtoa
(ii) A program can produce output by writing characters to a stream attac
data destination as shown in figure 18.2.

111111111
Input
Stream Output
- -- - - - - . Read Java Stream
1010101010 ~___;~ Program or Write
1010101010 Destination
Application

FIGURE 18.2

As shown in figure 1B- 2 , a java program uses an input stream to read data from a
source, one item at a time .
Similarly, a Java program can w rite information to a destination by using an output
stream, one item at time.

tS.3.1 Types of Stream


Java defines two types of streams. They are,

1. Byte Stream
It provides a convenient means for handling input and output of byte. Byte
stream supports byte (8-byte) 1/0 operations.
2. Character Stream
It provides a convenient means for handing input and output of characters.
Character stream suppo rts 16-bits Unicode character 1/0 and therefore can
be internationalized .

8.4 Stream Classes


The Java.io package contains nearly every class you might ever need tc perform
input and output (1/0) in Java. Java provides strong but flexible support for 1/0
related to files and networks too.

84 1
' • Byte Stream Classes
BYte stream is defined by using two abstract class at the top of hierarchy, they are
lnputStream and OutputStream as shown in figure 18.3.
[455)
Byte Stream

lnputStream OutputStream

FIGURE 18.3

18.4.1.1 InputStream Class


Java application uses an input stream to read data from a source. Source may bea
file, peripheral device, an array or socket. lnputStream class is an abstract class. It
is the superclass of all classes representing an input stream of bytes. Figure 18.4
shows the class hierarchy of Input stream classes.

FilelnputStream

FilterlnputStream
lnputStream

ObjectlnputStream

PipedlnputStream

FIGURE 18.4

[4561
ly used methods of lnputStream class are .•
co rn rnon
,-1ethods Description

~ b l i c abstract int read( ) throws reads the next byte of data from the
ioException{ } input stream. It returns -1 at the end of
file.

2 . public int read (byte b[ ]) throws Reads b.lengths bytes (i.e. an array of
10Exception{ } bytes) from the input stream into an
array. It returns -1 aN:he end of file.

3. public int available( ) throws Returns an estimate of the number of


10Exception{ } bytes that can be read from the current
input stream.

4. public void close( ) throws Is used to close the current input stream.
IOException{ }

18 .4.1.2 OutputStre am Class


outputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes as shown in figure 18.5. An output stream
accepts output bytes and sends them to some destination.

Fi leOutputStream

FilterOutputStre am
OutputStream t-~

PipedOutputStre am PrintStream

FIGURE 18.5

[457]
Commonly used methods of OutputStream class are :

Methods Description

1. public void write(int) throws ts used to write a byte to the cur;;;--


IOException { } output stream.

2 . public void write (byte b[]) throw~ Is used to write an array of byte to the
IOException { } current output stream.

3 . public void flush() throws Flushes the current output stream.


IOException { }
4 . public void close( ) throws Is used to close the current output
IOException { } stream.

18.4.2 Character Stream Classes


Java Byte streams are used to perform input and output of 8-bit bytes, where as
Java Character streams are used to perform input and output for 16-bit Unicode.
Character stream is also defined by using two abstract class at the top of hierarchy,
they are Reader and Writer.

Character Stream

Reader Writer

FIGURE 18.6
These two abstract classes have several concrete classes that handle Unicode
character.

18.4.2.1 Reader Stream Classes


Reader classes are functionally very similar to the input stream classes, except
input stream classes use bytes as their fundamental unit of information, while reader
streams use characters as shown in figure 18.7.
[4581
FileReader
Reader
FilterReader PushbackReader
StringReader
Piped Reader
FIGURE 18.7
The Reader class contains methods that are identical to those available in the
lnputStream class, except Reader is designed to handle characters.
18.4.2.2 Writer Stream Classes
Writer classes are functionally very similar to output stream classes, except output
stream classes are designed to write bytes, the writer stream classes are designed
to write characters as shown in figure 18.8.
BufferedWriter
CharArrayWriter
FilterWriter
Writer PrintWriter
StringWriter
PipedWriter
OutputStreamWriter FileWriter
FIGURE 18.8
The Writer class provides support for all output operations by defining methods that
are 1
·d •
ent1ca1 to those in OutputStream cla$$.
[459]
18.5 The Predefined Streams (or Standard Streams)
All the programming languages provide support for standard 1/0 Whoro ,
IJ.,rlr'
program can take input from a keyboard and then produce output on monitor fh ··
r:r,,
are three standard streams in Java : ·
1. Standard Input (System.in)

This is used to feed or enter the data to user's program by using keyboard
Keyboard is used as standard input stream and is represented as System.in.

2. Standard Output (System.out)

This is used to output the data produced by the user's program by usmg
monitor. Monitor is used to standard output stream and represented as
. System.out.

3. Standard Error (System.err)

This is used to output the error data produced by the user's program arid
usually a monitor is used to standard error stream and represented as
System.err.

18.6 Reading from Console


There are many ways to read data from the keyboard :

• lnputStreamReader

• Scanner
• DatalnputStream

• Console

18.6.1 InputStreamReader Class


To get user input, we can use the BufferedReader and lnputStreamReadtr
classes. The lnputStreamReader class reads the user's input whereas the
BufferedReader class butters the user's input to make it work more efficiently. Th858
classes are defined in java.lo package. To use these class, we need to reference
these in our code using following statement :

Import Java , lo. * ;


(dOI
tstreamRe ader class
lnPU
1.
inputStrea mReader class can be usocJ lo road data from koybonrd It

performs two tasks :

connects to input stream of keyboard



converts the byte-orient ed stream into character-o riented stream

autteredR eader class
2.
sutteredRe ader class can be used to read data either Character by Character

by using read() method or line by line by readline( ) method.

we use the object of buffered reader class to take inputs from the keyboard

Object of this class is created as ;

BufferedR eader br=new BufferedR eader(ne,,


InputStrea mReader( Svstem.in) ):
i . '1,
InputStre amReader Console inputs
is subclass of are read from s, ~tem.in
Reader class. It
converts bytes to
character.

In other ways :

InputStre amReader isr = new lnputStrcamRt.•adcr (S~ stern.in):

BufferedR eadcr br = new BuffrrcdRc.idt.•r (isr):

(a) Reading Character s

The read( ) method is used with BufteredR eader obJect to read ch A


this function returns Integer type value, therefore, we need to us type
to convert it into char type. Syntax is . •
int read() throws 1()(4":xceptlon

481
Example:

importjava.io.*;
class lnputchar
{
public static void main(String args[]) throws Exception
{
charc;
Buffered.Reader br-new Buffered.Reader(new
InputStream.Reader(System.in));
c=(char)br.readO; //Reading character
System.out.println(c); // Writing character
}
}
Output:
M
M

(b) Reading Strings


To read string we have to use readline() function with BufferedReaderclass's
object. Syntax is :
String read.Line() throws IOException

Example
Following example illustrate the readline() function.

importjava.io. *;
class Inputline
{
public static void main(String args[])throws Exception
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
Buffered.Reader br= new Buffered.Reader(isr);
[4621
text= br.readLineO; //Reading String
System.out.println(text);
}
}
output:
RaJll
-
RaJll
ScannerClass
18•6'2
The scanner c Iass 1s
· a c Iass .1n Java.u
. t"II package, which
. allows the user to rea d
values of various types. To use the Scanner class, we need to reference it in our
code. This is done with the keyword import as follows :
import java.util.Scanner;
Accepting keyboard input in Java is done using a Scanner object. There is a
System.in object in Java that can be used to get input in Java, but it is not very
functional. Instead, Java programmers usually prefer to use a Scanner object that
has been mapped to the System.in object. The System.in object (like the System.out
object) already exists and is available for use. However, you must create a Scanner
object.
Once you have created a Scanner object and "mapped" it to the System.in object
you can use the following methods to get input. Input always comes in to a Java
program as a string of characters (String type). There are methods that can be
used to convert the String to a character, an integer number, a floating-point number,
etc. Some commonly used Scanner methods are :
hasNextO //is something available to read? Returns true or false.
nextlntO //get an int
nextDoubleO //get a double
nexto //get a String ( delimited by whitespace)
nextLineO //get the rest of the line as a String
nextByteO // get a byte
nextShortQ // get a short
nextLongO // get along
nextFloatQ I I get a float
(463}
Example

Study the following program :

import java.util.Scanner;

class Sample 1
{

public static void main(String args[])


{
//String V aiiable
String name;

//Create Scanner Object


Scanners= new Scanner(System.in);

//Prompt the user for some input


System.out.println("What is your name? ");

//Read the string form keyboard and assigned to string variable naine
name=- s.nextO;

IN erify the input


System.out.println("Your name is "+name);
}
}

Output:
What is your name?
Raj
Your name is Raj

Here, to create a new scanner object of scanner class, statement is :


Scanners= new Scanner(System.in);
The new keyword is used to create new objects of a class. The object we are
creating is of Scanner class. In between round brackets we have to tell java that
this will be used for System Input (System.in).

[4641
4

et the user input, we can call into action one of the many methods available to
fog scanner object. Here, we have used next()
our new
method as :
Name= s.next( );

fJ<ample
Write a Java program to find the sum of two numbers.

import java.util.Scanner,

classAddl
{

public static void main(String args[])


{
int a, b, sum;
//Create Scanner object
Scanner s=new Scanner(System.in);
System.out.println("Enter two numbers ");

//Read numbers
a= s.nextlntO;
b = s.nextlntO;
sum=a+b;

//Wrtie Result
System.out.println("Sum = 11 + sum);
}
}

Output:
Enter two numben
10 20
Sum=30

(-465]
18·6·3 DatalnputStr eam Class
To get user input, we can also use the DatalnputStream class. This class is definect
m Java.io package.
While using DatalnputStream to take input from the user, exception handling is
required as we have done using BufferedReader class.

Example
r----- ------ ------ ------ ---
import java.io.*;
class Readlnput

public static void main(String args□)


{
String name;
DatalnputStream dis = new DatalnputStream(System.in);
System.out.println("What is your name?");
try /!handling exception
{
name = dis.readLine( );
System.out.println("Your Name is "+name);
}
c:..tch(Exception e)
{
Systern.out.println("An unexpected error occured! ");
}
}
}
Output:
What is your name?
Sushil
Your name is Sushil
[466)
s.1 writing to Console th d f
1 d print() are only used m
In last chapters pnntln() an cla ss of Outp e So or outp.ut on .conso
le. But
am a drived mented
there is a class PrintStre ut tream having a imple
.
. () .
ite , it can be used to write to the console •The s1mp1est form of write() is :
method wr
Va lu e)
vo id w ri te (i nt by te
.
strea m in byte form at by bytevaIue. Th e byteValue 1s
The method wr.ites to the n.
an integer but on ly low -o rder eight bits are writte
declared as

example
class DataWriteDemo
{
g args□)
public static void main(Strin
{
intx;
x='A'·
'
System.out.write(x);
System.out.write(\t');
x='P' ·
'
System.out.write(x);
System.out.write('\n');
}
}
O ut pu t:
A p

Files
18.8 Reading an d Writing and write
class es an d m ethod s that allows us to read from
In Java, there are many ite to files.
som e classes that are used to read from and wr
to files. Let us discuss

18·8·1 FileOutputStream Class


ve to
an outp ut stream fo r writing data to a file. If you ha
Java FileOutputStream is d data, we
en use FileO utp utStream. For character-oriente
Write Primitive values th
.
generally prefer FileWrlter
(467)
Example:
. . . *
unportJava.to. ;
class Writedemo

{ public static void main(String args□)


{
ti)'
{
FileOutputStream ofile ~ new Fil~tputStream("abc.tx.t");
String cname ="Dyal Smgh College ;
byte b[] _= cname.getBytes(); //converting string into byte array
ofile. wnte(b);
ofile.close( );
}
catch(Exception e) {System.out.println(e); }
}
}
Output:
Run the above program and open abc.txt file. We get the following conten
store in abc.txt file.
Dyal Singh College

18.8.2 FilelnputStream Class


Java FilelnputStream class obtains input bytes from a file. It should be used to read
byte-oriented data for example to read image, audio, video etc.
For reading streams of characters, we generally prefer FileReader.
Example
. . . *;
unportJava.10.
class readdemo
{
~ public static void main(String args□)
{
ti)'
{
FilelnputStrearn ifile =new FilelnputStream("abc.txt");
inti =O· ·
'
while((i =ifile.read())!=-1)
System.out.print((char)i);
}
ifile.close();
}
catch(Exception e) {System.out.println(e);}

Output:
Dyal Singh College

is.S.3 FileWriter Class


Java FileWnter class is used to write character-oriented data to the file.

Example
. . *
importJ8V8.IO. ;
class Sample

public static void main(String args□)


{
try
{
FileWriter fout =new FileWriter("xyz.txt");
fout. write(11Natraj Publication");
fout.close( );
}
catch(Exception e) {System.out.println(e);}
}
}
Output :
Run the above program and open xyz.txt file. We get the following
contents store in xyz.txt file.
Natraj Publication

[ 469]
18.8.4 FileReader Class
Java FileReader class is
us ed to read data from the
file .
Example
import java.io. *;
class Samplel
{
public static void main(String
args[]) throws Exception
{
FileReader fread =new FileR
eader("xyz.txt");
inti;
while( (i=fread. read( ))!= -1)
System.out.print( (char) i);

fread.clo se( );
}
}
Output :
Natraj Publications

18 .9 The transient Mod


ifier
Serialization is a proces
s of converting an objec
t into a sequence of byt
can be persisted to a dis
k or database or can be es which
sen t through streams. The rev
process of creating objec
t from sequence of bytes erse
is called deserialization.
A class must implemen
t Serializable interface
present in java.io packag
to serialize its object suc
cessfully. e in order
While serializing an ob
ject, if we don't.want cer
tain data member of the
serialized we can mentio
n it transient. The transien object to be
t modifier or keyword will
that data member from
being serialized. prevent
Example
class studentinfo impleme
nts Serializable
{
String name;
transient int rno;
}
In this example, rno wil
l not be serialized becau se it is transient.
(470)

_____......
fbe volatile Modifier
0
tS.1 ultithreaded program, sometimes, two or more thread
s share the same instance
In a.mble For eff1c1
· · ency cons,'d erat·
vana . .
ions, eac h thread can keep ·its own private copy
h a shared variable. '
of su C
or master) copy of the variable is updated at variou
The real ( s times such as when
nchronized method is entered. In some cases, all that '
really matters is that the
~:Stercopy of a variable always reflects its current state.
To ensure this, simply specify the variable as volat
ile, which tells the compiler that
. must always use the master copy of a volatile variab
le (or, atleast, always keep
,t ny private copies up-to-date with the master copy,
and vice versa). Also, accesses
~o the master variable must be executed in the precise
order in which they are
e)(ecuted on any private copy.
Volatile modifier will tell the JVM to be cautious of the
threads which runs concurrently
Essentially, volatile is used to indicate that a variab
le's value will be modified by
ditterent5~a ds.
Decla.t'ing a volatile Java variable means :
,I

• The value of this variable will never be cached threa


d-locally : all reads and
writes will go straight to "main memory"
Access to the variable acts as though it is enclosed
• in a synchronized block,
synchronized on itself.

18.11 Integrating Native Methods into Java Programs


A native method is a java method (either an instan
ce method or a class method)
whose implementation is written in another programm
ing language such as C.
The ability to write just one set of code in Java and
have it run on every system with
a Java run-time is one of Java's primary strengths.
The steps to creating native methods are as follow
s:
• Write Java Code
• Compile Java Code
• Create C header (.h file)
• Create C stubs file
• Write C code

• Create shared code library (or DLL)


• Run application

(471]
'

You might also like