0% found this document useful (0 votes)
7 views23 pages

Thread 2

Uploaded by

PRODYOT SINHA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views23 pages

Thread 2

Uploaded by

PRODYOT SINHA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

nput & O utp

ut
PART -1

File

Although most of the classes detined by


does not. It deals directly with
Ksnigind
java.io operate on streams, the File class
not specify how intormation isfiles and the file system, That is, thc File class does
retrieved from or stored in files, i describes the
nrcpcrties of a file itself. A File cbject is
2ssociated with a disk file, such as the used to obtaintime,or manipulate he
inforiation
and to navigate subdirectory hierarchies. permissions, date, and directory path.
The File class extends from the Object class
and is implenerted iin the following
interfaces namely Serializable and Comparable. As File
interface, its objects may be serialized and deserialized,irnplements
The File
the Serializable
also
the Connparable interface and thus enable implements
comparing theeyet path of two epmesetatiog
File objects
using the compare To() method.
Example-1
import java.io.*:
class FileTest

public staticvoid main(String[ ]args)


{
File f = newFile("FAljprglljbs note on IOljbsat workl\File Test java'):
if (f.exists( )
L direutoyonly
molKe
System.out.println(" Name of the file: "+f.getName( ));
System.out.printin(" Absolute path: "+f.getPath( )): omhdirs
System.out.printin(" Parent directory: "+f.getParent( ): wth
System.out.printn(" Size of the file (in Bytes): "+f.length( ):
System.out.println(" Is it hidden: "+f.isHidden( ));
System.out.println(" Is editable: "+f.canWrite( )); dlreltooY
else

System.out.println(" File "+f.getName( )+" not found");

returns true if called ona file and false


There is a method by the name isFile(), which
if calied on a directory.
methods. The first is rename To(), shown here:
File also includes two useful utility
boolean rename To(File newName)
becomes the new naC of he invoking
Ticre, the filcnane specilicd by OwNa: renamed.
succoss and false il the ile cannot be
le objecl. It willreturn tiuo upo)
1ptu3CNlUU Uy
melhod is doloted ) wlhich dulcles lhe disk ile
Tne second utility
path of the invokingFile object. It is shown here:
boolean delete() directory iS enply. Uelele()
delete adirectory if the
delete( ) to
TOu can also use be removed.
true if it deletes the file and false if the file cannot
eturns
sub-directories in a path name
those that separate the platforns Wo Gan usO
IN. B. File separators are same for different oyiLm I.
not be In wilch ho
These characters which
may
uses the dofault sOparal0I of lhu ()S
re.separator,
statements are equivalent:work|\FileTest.java");:
executed. Hence the next two
File("F:AVjprallibs note on IOljbs at jbs note on
1: File f= new File("E:"+File.separator+"iprg"+File.separator+
L. Fle f= new work"+File.separator+"FileTestjava"), J
I0"+File.separator+"ibs at

Random Access Files


files are used
has a RandomAccessFile class. Random access
Tne java.iopackage Sequential file access requires
to read and write data from anvwhere in a file. information.
before finding the required
Scanning each line of data in the file
assume that a file
up an example to understand random access. Let us
Let us take
has the following line of data:
10, Arun Sen, 85.5
30, Barun Dutta, 78.0
20, Kiran Sarkar, 90.3
50, Mala Majumdar, 86.8
third record in the list, sequentialaccess
In order to find the student with roll 20. the
records. But using seek operation in the
Would require passing through the first two roll 20 can be found without having
random access mode, "Kiran Sarkar" with
passing through the first two records.
Object and it implements
The RandonAccessFile class is extended from the class used while the class is
Datalnput and DataQutout interfaces. The argument both.
instantiated, help decide while the object will be used for reading or writing or
Syntax:
1. RandomAccessFile(File fileObj, Stringaccess)
throws FileNotFoundException
2. RandomAccessFile(String filename, String access)
throws FileNotFoundException
In the first form, fileObj specifies the name of the file to open as aFile object. In the
access
second form, the name of the file is passed in_ filename. In both cases,
determines what type of file access is permitted. If it is "', then the file can be read,
but not written. If it is "wthen the file is opened in réad-write mode. If it is "rws" the
file is opened for read-write operations and every change to the file's data or
metadata will be immediately written to the physical device. If it is "wd", the file is
opened for read-write operations and every change to the file s data will be
immediately written to the physical device.
For example:
new RandomAccessFile("input.txt", "":
new RandomAccessFile("inout.txt", "rw"):

The RandomAccessFile class supports the concept of a file pointer that is used to
indicate the current location in the file. At the time of creation of the file, the file
3
pointer is set to 0,
numbers of bytes that which indicates the
are read or beginning
written, move of the
the file pointerfile. Subsequently. the
This manipulation of the File
three methods: skipBytes, seek,pointer is accordingly.
achieved this class, using the following
in
public int skipBytes(int n) and getFile Pointer.
throws IOException
This method moves the file
publicvoid seek(longpointer
pos)
in the forward
direction by "n" bytes.
throws IOException
This method is used for
specified by "pos". positioning the file pointer exactly before the byte that is
public long getFile Pointer()
throws IOException
This method returns the current
offset in this file.
Example-2
import java.io.*;

public class RandomAccessTest


static String fileName ="random.txt".
final static int CHAR_POSITION = 2:
public static void main(Stringl ]args)
try

RandomAccessTest random = new RandomAcuessTest();


random.writeAlpha();
random.readAlpha();
catch(Exception e)
System.out.println(e);

public void writeAlpha() throws IOException


File dataFile = new File( fileName );
RandomAccessFile raFile = new RandomAccessFile(dataFile, "rw");
System.out.print(" Data written to the file random.txt are: ");:
for(int i= 65; i<=90; i++)
raFile.writeChar( i);
System.out.print(char) i+"");
System.out.prinln():
raFile.close):

public void readAlpha() throws IOException


{
try
{ fileName );RandomAccessFile(dataFile."r");
File dataFile = new File(
RandomAccessFile raFile = new randon.txl le: ");
Random alphabets from thefile
System.out.print("
long length = raFile.length(); islongth; it 2*CHAR_POSITION)
CHAR_POSITION;
for(int i :
raFile.seek( i);
System.out.print( raFile. readChar()+" ");
raFile.close( ):
catch(FileNotFoundException e)

System.out.println(e);
System.exit(1 );
catch(|OException e)
e.printStackTrace();

Creating Directories
Another twO useful File utlity methods are mkdir( ) and mkdirs( ). The mkdir( )
method creates a directory, returning true on success and false on failure. Failure
indicates that the path specified in the File object already exists, or that the directory
cannot be created because the entire path does not exist yet. To create a directory
for which no path exists, use the mkdirs( ) method. It creates both a directory and all
the parents of the directory.

Streams

Input/output in Java is stream based. Java treats all information,


source or destination, as stream. Data that is read or written in a regardless
of the
treated as a stream of data, continuous bytes of data that Java program is
out. These bytes are read from or written to files or keep coming in, or going
sockets or Internet connections.
Streams are dovice independent.
Astream in Java is any nath of
following are some pairs of sourcesinformation from the source to a destination. The
and destinations:
A keyboard and a monitor
Apage of text on a
monitor and afile on a hard drive
Afile on a hard drive and a
A WEB server and a monitor
A keyboard and a
browser
A text file and a string
printer
The stream process davd 1s well abstracted. And
Janguage for network communication can be treated as an ideal
Tho following is the Basic
Step 1: Open astreamalgorithm
from
for reading using a
a data source to a stream:
Sten 2: While data is Java program.
available in data source, read
Step 3: Close the stream. the data.
The following is the basic
algorithm for writing using a stream:
Step 1: Open a stream from a
Step 2: While data is available Java program to a data source.
in Java program, write the
Step 3: Close the stream. data to data source.

Streams in Java are well organized and are classified as


following two groups: belonging to one of the
1. Byte streams
2. Character streams

These two streams allow us to access data in a sequential manner.

Byte streams are used to transfer 8 bits of data, while character streaims work with 16
bit Unicode characters. Byte streams are represented in Java as:
1. InputStream class
2. OutputSteram class

Character streams are represented as:


1. Reader class
2. Writer class

Java takes an international approach to its characters, using two bytes to represent a
character. The InputStream and OutputStream classes cannot process Unicode
characters efficiently, Reader
characters in an efficient manner. To handle Unicode
and Writer classes were created in Java.

The InputStream class


of data.
class that is used for reading 8-bit bytesthat
The InputStream class is an abstract Classes are
InputStream class is extended from the. Object class. returns the next
The required to implement a method that
subclasses of InputStream are that is being read. Now we
should discuss with its
byte of data from the stream
subclasses.

class
1.The ByteArraylnputStream a byte array
implementation of an input stream that uses byte arrayto
ByteArraylnputStream is an requires a
constructors, each of which
class has tWo
as the source, This
provide the data source:
ByteArrayinputStream(byte array[ J) numBytes)
1. ByteArrayinputStream(byte arrayl ], int start, int
2.
Here, "array" is the input source. The secotnd constructor cratt nInputstrOU)
trom asubset of your byte array that begins with the character at the index specified
by "start" and is "numBytes" long.
A ByteArraylnputStream implements both mark( ) and reset( ). However, if mark(
has not been called, then reset( )sets the stream pointer to the start of the stream
which in this case is the start of the byte array passed to the constructor.

Example -3
This example slhows how lo use the rosel() melhod to reud tho samo input twice. In
this case, we read and print the letters "abc" once in lowercase and then again in
uppercase. /

import java.io.";
class ByteArraylnputStreamTest
public static void main(String args[) throws IOException
String tmp = "abc";
byte bl] =tmp.getBytes();
ByteArraylnputStream in =new ByteArraylnputStream(b);
for (int i=0; i<2; it+)
int c;
while ((c = in.read() =-1)
if (Ë == 0)

System.out.print(char) c);
else
{
System.out.print(Character.toUpperCase((char) c);
System.out.printin();
in.reset():
fluhen ie trnm
OUTPUT
Fjprgybs note on I0ybs at work>java
abc
ABC ByteArraylnputStreamTest
2.The
FilelnputStreamclass
The FilelnputStream class
from afile. Its tWO most Common creates an InputStream that you can use to
read bytes
constructors
1. FilelnputStream(String filepath) are shown here:
2. FilelnputStream(File fileObj)
Fither can throwa bete
FileNotFoundException.
file, and "fileObj" is a File object that Here. "filepath" is the full path name of a
describes the file.
Example - 4

import java. io.*;


class FilelnputStreamTest
public static void main(String argsl) throws Exception
int size;
InputStream f= new FilelnputStream("FilelnputStreamTest.java");
System.out.printin("Total Available Bytes: " +(size =f.available(0)):
System.out. println(" Content of the file: "):
for (int i=0; i< size; it+)
System.out.print((char) f.read()):

3. The BufferedlnputStream class


very Common performance optimization. Java's
Buffering /O is InpulStream into a buffered
BufferedlnputStream class allows you to "wrap" any
improvement.
stream and achieve this performance
BufferedlnputStream has two constructors:
BufferedlnputStream(InputStream inputStream)
BufferedinputStream(InputStream inputStream, int bufSize)
the
buffered stream using adefault buffer size. In the second,
The first form creates a "bufSize". Use of sizes that are
multiples of memory
passed in
size of the buffer is
can have asignificant positive impact on performance.
page, disk block, and so on
implementation-dependent. An optimal buffer size is generally
This is, however, amount of memory available, and how
operating system, the necessarily reguire
dependent on the host make good use of buffering
doesn't
8,192 bytes.
configured. To is around
the machine is
of sophistication. Ago0d guess for as0zealways a good idea. That
quite this degrèe stream is
rather small buffer to an I/O trom the disk or network and store
and attaching even a data
system can read blocksS ofare reading the data a byte at a time out
way, the low-level you of the
buffer. Thus, even if memory over 99.9 percent
the results in your manipulating fast
you will be
of the InputStream,
time.

Example -5

import java.lo.";
BufferedInputStreamTest
public class
{
publicstatic void main(Stringl ] args)
if(args. length!=1)
BufferedlnputStreanm <filename>"),
System.out.printin(" Usage:
System.exit(1);
int count = 1;
try
FilelnputStream fis =new FilelnputStream( args[(0] );
BufferedlnputStream bis = new BufferedlnputStream( fis );
int b;
while( (b= bis.read()) =-1)
{ 4 stoao
System.out.print( (char) b );
if( b ==n')
countt+;

catch(|0Exception e)

e.printStackTrace();

System.out. printin("nn Number of lines in the file "+args(0]+", "+count);:

4.The PushbacklnputStream class


One of the novel uses of buffering is the implementation of pushback. Pushback is
used on an input stream to allow a byte to be read and then returned (that is,
"pushed back') to the stream. The PushbacklnputStream class implements this idea.
It provides amechanism to "peek" at what is coming from an input stream without
disrupting it.
PushbacklnputStream has the following constructors:
1. PushbacklnputStream(InputStream inputStream)
2. PushbacklnputStream(InputStream inputStream, int numBytes)
The first form creates a stream object that allows one byte to be returned to
stream. The second form creates
the input
stream that has a pushback buffer that is
"numBytes" long. This allows multiple bytes to be returned to the input stream.
Example-6

import java.io.*;
class PushbackinputStreamTest
public static void main(String args[ ]) throws I0Exception
String s= "if (a= 4) a = 0:\n":
byte buf[]= s.getBytes():
ByteArraylnputStream
PushbackinputStream
in = new
f = new ByteArraylnputStream(buf);
int c;
while ((c= f.read()) !=1)
PushbackinputStream(in):
switch(c)
case '=': if ((c = f.read()) =='=)

System.out.print(".eq.");:
else
{
System.out.print("<-");
I/void unread(int ch) - This form pushes back the low-order
byte of "ch".
f.unread(c);
break:

default: System.out.print(char) c);

5. The SequencelnputStream class


The SequencelnputStream class allows you to concatenate multiple InputStreams.
The construction of aSequencelnputStream is different from any other InputStream.
A SequencelnputStream constructor uses either a pair of InputStreams or an
Enumeration of InputStreams as its argument:
1. SequencelnputStream(InputStream first, InputStream second)
2. SequencelnputStream(Enumeration streamEnum)
Operationally, the class fulfills read requests from the first InputStrcam until it runs
out and then switches over to the second one. In the case of an Enumeration, it will
continue through allof the InputStreams until the end of the last one is reached.
Example -7
PThis example creates a Vector and then adds two filenames to it. It passes that
vector of names tothe InputStreamEnumerator class, which is designed to provide a
wrapner on the vector where the elements returned are not the filenames but rather
opon FilolyputStroams on thoso names. The SoquoncelnputStiecamopens each file
in turn, and this example prints the contents of the two files.

import java.io.';
import java,util.";
class InputStreamEnumeralor lmplemenls Enumerallon
private Enumeration files:
public InputStreamEnumerator(Vector files)

this.files =files.elements();
public boolean hasMoreElements()
{
return files.hasMoreElements():
public Object nextElement()
try

return new FilelnputStream(files.nextElement().toString()):


catch (Exception e)
return null;

public class SequencelnputStreamTest


{
public static void main(String args[) throws Exception
int c;
Vector files = new Vector();
files.addElement("F:ljprg/jbs note on IOljbs at work/FileTest.java");
files.addElement("F:ljprg/jbs note on IOljbs at work/RandomAccessTest.java"):
InputStreamEnumerator e =new InputStreamEnumerator(files);
InputStream input =new SequencelnputStream(e);
while ((c = input.read() !=-1)
System.out.print((char) c);
input.close():

The OutputStream class

The OutputStrean class is an abstract class that is used for writing data in
of 8-bits byte. Classes that are subclasses of the 1orm
OutputStream are requireo
implement at least one menod, which returns one byte of data as output. However,0
the subclasses can override the methods provided by the
OutoutStream class TO
better efficiency, or to add some more features. Now we should
subclasses. discuss witn

1.The ByteArrayOutputStreamn class


The
ByteArraylnputStream
OutoutStream) class is used as an
that is used for writing data into a byteOutputStream (as it extends
huffer internally that stores bytes that are to be array. This class maintains a
written to a byte array.
Example - 8

import java.io.".
public class ByteArrayOutputStreamTest
publicstatic void main(String[ ] args) throws
IOException
try

String strText;
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Give any line of text: "):
strText = br.readLine( );
byte byteArray1[] = strText.getBytes( );
ByteArrayOutputStream ba =new ByteArrayOutputStream( ):
ba.write(byteArray1):
System.out.println(" The ByteArrayOutputStream holds: "+ ba.toString());
System.out.printin(" Now ByteArrayOutputStream copied to a byte
array... ");
byte byteArray2[] = ba.toByteArray( ):
for(int i= 0; i< byteArray2.length; i++)
System.out.print((char) byteArray2[i] ):

catch(IOException e)
e.printStackTrace( ):

2. The File OutputStreamclass


FleOutputStream creates an OutputStream that youcan use to write bytes to a file.
Its most commonly used constructors are shown here:

1. FileOutputStream(String filePath)
2. FileOutputStream(File fileObj)
3. FileOutputStream(String filePath, boolean append)
4. FileOutputStream(File fileObj, boolean append)
Thoycan throw a FiloNolFoundExcoption or a SocurilyExcoplion. Here, "filePath" is
the full path name of a file, and "leObj" is a File object that describes the file If
"append" is "true", the file is opened in append mode. Java 2, version 1.4, added the
fourth constructor.
Creation of a FileQutputStream is not dependent on the fle already existing.
File OutputStream willcreate the file before opening it for outputwhon youcrealo tho
Object. n the case where youattempt to open a read-only file, an lOException will be
thrown.

Example -9
import java.io.":
public class FileQutputStreamTest
public static void main(Stringl ] args)
try

BufferedReader br new BufferedReader(new


InputStreamReader(System.in));
System.out.print(" Give any line of text: "):
String str = br.readLine( );
FileOutputStream out = new FileOutputStream("ibs.txt");
PrintStream p = new PrintStream( out );
p.println( str );
System.out.printin("The given line of text has been written to the file
l"jbs.txtl".....");
p.close( ):
catch(Exception e)
e.printStackTrace();

3. The BufferedOutputStream class


ABufferedOutputStream is similar to any
added flush( )method that is used to ensure OutputStream with the exception of an
the actual output device. Since the point ofthat
a
data buffers are physicallywriten to
performance by reducing the number of times BufferedOutputStream is to improve
may need to call flush) to cause any data thatthe system actually writes data, you
buffered input, buffering output does not provideisadditional
in the buffer to get written. Unlike
output in Java are there to increase functionality.
performance. Here are the twoBuffers
for
constructors: available

BufferedOutputStream(OutputStreamoutputStream,
BufferedOutputStream(OutputStream outputStream) int bufSize)
The first form creates a
form, the size of the bufferbuffered stream using a
is passed in bufSize. buffer of 512 bytes, In the second

Example- 10
import java.io.";
13
public class BufferedOutputStreamTest
publicstatic void
try
main(String) args) throws IOException
if(args.length != 2)
System.err.println("
System.err.println(" Usage the following
java commandline:");:
<buffer-size>");
System.exit(1); BufferedOutputStreamTest <text-file-name>
FileOutputStream
int bufferSize = fos = new FileOutputStream( args[0] ):
Integer.parselnt(
BufferedOutputStream bos= newargs(1]
);:
DataOutputStream dos = new BufferedOutputStream(fos, bufferSize);
for(int i=65; 0<=90; i++) DataOutputStream(bos );
dos.writelnt( i);
System.out.print( (char)i+"");
dos.flush( );
}
catch(llegalArgumentException e)
System.err.println(" Buffer size can not be ZERO or -(VE)!!!");
System.exit(0);
catch(FileNotFoundException e)
System.err.println(" The specified file "+args[0]+" is not available or
corrupted...");
System.exit(0);

OUTPUT
F:jprgljbs note on IOljbs at work>java BufferedOutputStreamTest abc.txt 100
ABC DEFGHIJKLMNOPQRSTUVWXYZ */

o The PrintStream class

We might want to write the data in the same underlying platform's representation of
the data type. The PrintStream class enables us to do this. The PrintStream class
enables uS to do this. The platform's defaut character encoding is used to convert
characters written using PrintStream to bytes. It is more useful when charactes,
rather than bytes, are to be written.
Java's PintStream objects support the printt and println( ) methods for all types,
including Object. If an argument is not a simple type, the PrintSlreamn methods will
call the obloct's (oSting) melhod and thenprint the result.
Example - 11
import java.io.":
public class PrintStreamTost

public static void main(String[ ] args)


try
{
BufferedinputStream bis =new BufferedlnputStream(new
FilelnputStream("PrintStreamTest.java");
PrintStream ps = new PrintStream( new BufferedOutputsti eam( new
FileOutputStream("random.txt"))):
/Setting the standard input, output, and error mode.
System.setin( bis );
System.setOut( ps ):
System.setErr( ps );
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in):
String str;
while( (str = br.readLine()) !|= null )

System.out.println(str);
System.out.println("
ps.close( );
Output is written to the file
\'redirectFile.txtl"...."):
catch(FileNotFound Exception e)
{
e.printStackTrace( ):
} System.exit(0);
catch(|0Exception e)
e.printStackTrace( ):
Input & O utput PART -2
The Character Streams
We have so far ways of
provide sufficient reading and writing
Work directly
classes
functionality
with Unicode to handle any tvpedataof asWO bytes. Byte stream classes
and Writer discUssed. At thecharacters. operation,
are In but
top of the this section, several of the they cannot
abstract classes. character stream hierarchies arecharacter /O
the Reader
Reader
Reader is an
This abstract abstract class that
class provides the defines Java's model of
streams that are used for reading API along with partial streaming character input.
will throw an 16-bit characters. Allimplementation of all
of the methods in. this, reader
described below:IOException on error conditions. Method of this class
class are briefly
1. public abstract void
stream. close) - throws IOException and this
method closes the
2. public void mark(int
readAheadLimit)
marks the present position - throws
in the stream. IOException and this method
attempt to reposition the stream to this point.Subsequent
Not
calls to reset() will
Support the mark() operation. all character-input streams
(readAheadLimit - Limit
characters that may be read while still preserving the mark.on the number of
many characters, attempting to reset the stream After reading this
than the size of the input buffer will cause a may
fail. limit value larger
A
size is no smaller than limit. Therefore new buffer to be allocated whose
3. public boolean large values should be used with care.]
markSupported() Tell whether this stream supports
mark() operallon. The default implementation always the
Subclasses should override this method. returns false.
4. public int read() - throws IOException. This method
This method will reads asingle character.
block until a character is available, an I/O
end of the stream is reached. Subclasses that intend toerror occurs, or the
support efficient
single-character input should override this method.
5. public int read(charl ] cbu) - throws IOException. Attempts to read up to
buffer.length characters into buffer and returns the. actual number of
characters that were suCcessfully read. -1 is returned when the end of the file
is encountered.
6. public abstract int read(charf ] buffer, int offset, int numChars) throws
IOException .Atempts to read up to numChars characters into buffer starting
at bufferoffset, returning the number of characters successfuly read. -1 is
returned when the end of the file is encountered,
7. publc booloan roady() - throws /OEXcption. Returns true if the next read()
is quaranteed not to block for input, false otherwise. Note that returning false
does not guarantee that the next read will block,
8. public vold reset() throws lOException. It resets the stream. If the stream
has been marked, then attempt to reposition it at the mark. If the stream has
resel I In some Way approprlale to /Te
not been marked, then allempt torepositioning it to its starting point. Not all
particular stream, for example by operation, and some support
character-input streams suppot the reset()method throws IOException - If the
This
reset) without supporting mark(). the mark has been invalidated, or if the
stream has not been marked, or if
some other l/O error occurs. characters.
stream does not support esot(), or if This method skips
9. public long skip(long n) - throws /OException. available, an I/O error
This method will block until some characters are to
charactors
reached. "n" - The number of
Occurs, or the end of the streamn Is
number of characters actually skipped.
skip. It returns the

Writer
methods
streaming character output. Allof the
Writer is an abstract class that defines throw an /OException in the case of errors.
and
in this class return a void value
Method of this class are briefly described below:
IOException - Close the stream, flushing
1. public abstract void close() throws
it first.
IOException - Finalizes the output state so
2. public abstract void flush() throws flushes the output buffers.
that any buffers are cleared. That is, it - Write a single character. The
IOException
3. public void write(int c) throws low-order bits of the given
character to be written is contained in the 16
integer value; the 16 high-order bits are ignored. Write an array of
4.. public void write(char[ cbuf) throws IOException
characters. Here "cbuf" Array of characters to be written.
throws IOException
5. public abstract void write(charll cbuf, int off, int len)
Array of characters. "off" -
Write a portion of an array of characters. "cbuf" - Number of characters to
Offset from which to start writing characters. "len" -
write.
Write a string.
6. public void write(String str) thrOws IOException WVrite a portion
7. public void write(String str, int off, int len) throws IOException. characters.
of astring. "str" -A String. "off" - Offset from which to start writing
"len"- Number of characters to write.

FileReader
The FileReader class creates aReader that you can use to read the contents of a
file. Its two most commonly used constructors are shown here:

D FileReader(StringfilePath)
O FileReader(File file Obj)
Either can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a Fle object that describes the file.
Example- 12

import java.io.";
class FileReaderDemo

public staticvoid main(String args[) throws Exception


EileReader fr =new
BufferedReader
String s;
br =new FileReader("FileReaderDemo.java"):
BufferedReader(fr):
while((s = br.readLine() != null)
System.out.println(s);:
fr.close();:

FileWriter

FileWriter creates a Writer that you can use to write to a file. Its most
constructors are shown here: commonly used

o FileWiter(String filePath)
o FileWriter(String filePath, boolean append)
D FileWriter(File fileOb)
FileWriter(File file Obj, boolean append)
They can throw an IOException. Here,filePath is the full path name of a file, and
fileObi is a File object that describes the file. If append is true, then output is
appended to the end of the file. Java 2, version 1.4, added the fourth constructor.
Creation of a FileWriter is not dependent on the file already existing. FileVWriter will
create the file before opening it for output when you create the object. ln the case
where you attempt to open a read-only file, an /OException will be thrown.
Example -13
import java.io.";
public class FileWriterDemo
publlc static vold maln(String[ ] args)
try
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter a line of text: ");
String str = br.readLine():
/The first, file1.txt, will contain every other character from the sample.
char buffer ]= new char[str. length()]:
str.getChars(0, str.length(), buffer, 0);
FileWriter f0 = new FileWriter("file1.txt");
for (int l=0; |< buffer.length; | + 2)
f0.write(buffer(j]);
f0.close():
II The second, file2.txt, will contain the
entire set of characters.
FileWriter f1 =new FileWriter("file2.txt");
f1.write(buffer);
f1.close();
IlThe third, file3.txt, willcontain only the
FileWriter f2 = new FileWriter("file3.txt"); last quarter.
f2.write(buffer, buffer. length - buffer.length/4, buffer.length/4);
12.close();
catch(|0Exception e)
{
e.printStackTrace();

CharArrayReader
CharArrayReader is an
as the source. This class implementation of an input stream that
uses a character array
has two
array to provide the data source: constructors, each of which requires a character
o CharArrayReader(char array[)
o
CharArrayReader(char array[), int start, int numChars)
Example-14
import java.io.";
public class CharArrayReaderDemo
public static void
main(String argsl) throws IOException
String tmp="abcdefghijklmnoprstuvwxyz";
int length =
tmp.length():
char c[ ] = new
tmp.getChars(0,charf[length);
length, c, 0);:
CharArrayReader
CharArrayReader
int i,
input1 = new
input2 = new CharArrayReader(c);:
System.=oinput1.read())
ut.print("inputi=is:1)");, CharArrayReader(c, 0, 5);
while(i

System.out.print(char)i);
Systeem.m.o=outut..ppririnntt(in"i();nput2 is:");
Syst
while((i input2.read() =1)
System.out.print(
System.out.printin():
charn)i);
19

CharArrayWriter
CharArrayWriter is an
implteerment
destination. CharArrayWri has atwo
tion of an output stream that uses an
o CharArrayWriter() constructors, shown here: array as the

o CharArrayWriter(int numChars)
In the first
form, a
created with a size buffer
equal to
with. a default size is
that created. In the second, a
field of specified by
CharArrayWri
The number of ter. The buffer size will numChars.
characters be The buffer is held inbufteriS
the bur
held by the buffer isincreased automatically, if needed.
CharArrayWriter. Both buf and count are contained in the count field of
protected fields.
Example-15
import java.io.*:
public class CharArrayWriterDemo
public static void
main(String[ ] args) throws IOException
CharArrayWriterbr = newnewCharArrayWriter();:
BufferedReader
cw=
InputStreamReader(Syst BufferedReader(new
System.out.print("em.Enter
in)); aline of text: ");
String str= br.readLine():
char charBuf[ ]=new
charfstr.charBuf,
str.getChars(0, str.length(), length()):O);
cw.write(charBuf):
System.out.println(" CharArrayWriter object contains: "+cw.toString ());
System.out.print(" Character array contains: ");
char c[ ]= Cw.toCharArray();
for(int i = 0; i<c.length; i++)
System.out.print( c[ i]):
System.out.printin ():
FileWriter-fw =new FileWriter("array. txt"):
CW.writeTo( fw );
fw.close(0:
Cw.close():
System.out.printin(" Array contents are written to the file l"array.txtl"..":

BufferedReader
BufforodReador lmprovos performance by bullorlng lnput. It has tWo conslruclors:
o BufferedReader(Reader inputStream)
bufSize)
O BufferedReader(Reader input Stream, int
In the
The first form creates a buffered character stream using a delault bulfer slze.
second, the size of the buffer is passed in bufSize.

As ls the case with the byte-orlented stream, buffering an Input character stream also
the
provides the foundation required to support moving backward in the stream within
available buffer. To support this, BufferedReader implements the mark) and reset()
methods, and BufferedReader.markSupported( ) returns true.
Example - 16
import java.io.";
class Buffered ReaderDemo

publicstatic void main(String args) throws IOException


String s ="This isa 8&copy; copyright symbol but this is &copy : not.\n";
char buf[= new char[s.length()):
S.getChars(0, s.length(), buf, 0);
CharArrayReader in = new CharArrayReader(buf);
BufferedReader f= new BufferedReader(in);
int c:
boolean marked = false;
while ((c = f.read() !=-1)
switch(c)
case '&: if (!marked)

f.mark(32);
marked = true;
else

marked= false:
break:

case ': if (marked)

marked= false:
System.out.print("(c)");
else

System.out.print(cha) c); !
break,
case'": if (marked)
marked= false;
f.reset():
System.out.print("&");
else.
{
Sy_tem.out. print(char) c);
break;
default: if (!marked)

System.out.print((char) c);
}/ switch-case
}I/ while
ii main()
}/ end of the class

BufferedWriter
A BufferedWriter is a Writer that adds a flush( ) method that can be used to
that data buffers are physically written to the actual output stream. ensure
BufferedWriter can increase performance by reducing the number of timesUsing data isa
actually physically written to the output stream. A BufferedWriter has these two
constructors:

BufferedWriter(Writer outputStream)
BufferedWriter(Writer outputStream, int bufSize)
The first form creates a buffered stream using a buffer with a default size. In the
second, the size of the buffer is passed in bufSize.
In general, a Writer sends its output immediately to the
stream. Unless prompt output is required, it is advisableunderlying character or byte
to wrap a BufferedWriter
around any Writer whose write() operations may be costly, such as
OutputStreamWriters. For example, FileWrters and
PrintWriter out = new PrintWriter(new BufferedWriter(new
will buffer the PrintWriter's output to the file. FileWriter("foo.out")):
print() method would cause characters to be Without buffering, each invocation of a
written immediately to the file, which can be veryconverted into bytes that would then be
inefficient.
Example - 17
import java.io.";
class BufferedVriterDemo
public static void main(String[ ]args) throws IOException
BufferedReader br = new BufferedReader(new
InputStream Reader(System.in));
System.out.print(" Give roll of the student: "):
int roll = Integer.parselnt(br.readLine());
Syste.out.prlnt(" Glve nane of the student: "):
String name = br.readLine();
System.out.print(" Give marks percentage of the studont: ");
float mp =Float.parseFloat(br.readLine()):
Writer out = newFileWriter("student. txt");
BufferedWritor bw new BufferodWriter(out),
PrintWriter pw =newPrintWriter(bw);
pw.println(roll);
pw.println(name);:
pw.println(mp);
pw.close():
System.out.printin(" Student data written to the file student.txt....");
}

PushbackReader

The PushbackReader class allows one or more characters to be returned to the input
i's stream. This allows you to look ahead in the input stream. Here are its two
constructors:

D PushbackReader(Reader inputStream)
o PushbackReader(Reader inputStream, int bufSize)
The first form creates a buffered stream that allows one character to be pushed back.
In the second, the size of the pushback buffer is passed in bufSize.
PushbackReader provides unread( ), which returns one or more characters to the
invoking input stream. It hasthe three forms shown here:
void unread(int ch)
o void unread(char buffer)
o void unread(char bufferl], int offset, int numChars)
The first form pushes back the character passed in ch. This wilbe the next character
returned by a subsequent callto read(). The second form returns the characters in
buffer. The third form pushes back numChars characters beginning at offset from
buffer. An IOException will be thrown if there is an attempt to return acharacter when
the pushback buffer is full.

Example 18
import java.io.";
class PushbackReaderDemo

public static void main(String args[ ]) throws IOException


{
String s = "if (a == 4) a = 0;n";
char buf[0=new char[s.length()):
s.getChars(0, s.length(), buf, 0);
CharArrayReader in = new OCharArrayReader(buf);
PushbackReader f= new PushbackReader(in):
int c;
while (c =f.read()) !=-1)
{
switch(c)
case '=': if ((c = f.read()) == '=')
System.out.print(". eq.");
else

System.out.print("<.");
f.unread(c);
break;
default: System.out.print(char) c):

PrintWriter

PrintWriter is essentially acharacter-oriented version of PrintStream. It provides the


constructors:
formatted output methods print and println(). PrintWriter has four
D PrintWriter(OutputStream outputStream)
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
PrintWriter(Writer outputStream)
boolean flush OnNewline)
O PrintWriter(Writer outputStream,
every time
flushOnNewline controls whether Java flushes the output stream place. If
where takes
flushOnNewline is true, flushing automatically
printin( ) is called. If automatically
is not automatic. The first and third constructors do not
methods for all
false, flushing support the print( ) and printin()
flush. Java's PrintWriter objects the PrintWriter methods
including Object. If an argument is not a simple type,result.
the
types,
call the object's toString()method and then print out
will

You might also like