Thread 2
Thread 2
ut
PART -1
File
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.*;
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
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
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.
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
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();
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:
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
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
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( ):
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
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 */
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
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
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
f.mark(32);
marked = true;
else
marked= false:
break:
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
System.out.print("<.");
f.unread(c);
break;
default: System.out.print(char) c):
PrintWriter