[go: up one dir, main page]

0% found this document useful (0 votes)
14 views36 pages

CH 3 - Part 2

The document discusses Java I/O streams and classes for file handling. It describes InputStream, OutputStream, Reader and Writer abstract classes and common stream classes like FileInputStream and FileOutputStream. Methods of File class for file operations and RandomAccessFile class for random access to files are also covered.

Uploaded by

yashsayani1234
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)
14 views36 pages

CH 3 - Part 2

The document discusses Java I/O streams and classes for file handling. It describes InputStream, OutputStream, Reader and Writer abstract classes and common stream classes like FileInputStream and FileOutputStream. Methods of File class for file operations and RandomAccessFile class for random access to files are also covered.

Uploaded by

yashsayani1234
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/ 36

R.P.

Bhalodia BCA College

CH 3

Part-2
File Handling

1
Stream and its types(Input,Output, Character, Byte)
 Java’s stream-based I/O is built upon four abstract classes: InputStream,
OutputStream, Reader and Writer.
 Streams are the most important part in creating the applications like Data
Input from keyboard and output on the System Output Devices.
 Actually, until now we have used input and output streams in our
applications but we don’t know explicitly that we are using streams.
 In java, for the Input / Output (IO) operations, we have two major
packages. One is the java.io package which was available from java 1.0
and then later from java 1.4 we get java.nio package (New IO Package).
Remember that: the java.nio package is not a replacement of the
java.io package.
Both are different ways of performing IO operations. The java.io package
has classes and interfaces which help in file management and stream-based IO,
and the java.nio has classes and interfaces for the buffer-based IO. Various
important classes of java.io package are given in next table.
The Java I/O Classes and Interfaces:
BufferedInputStream FileWriter PipedInputStream
BufferedOutputStream FileInputStream PipedOutputStream
BufferReader FileOutputStream PipedReader
BufferedWriter FilterReader PipedWriter
ByteArrayInputStream FilterWriter PrintStream
ByteArrayOutputStream InputStream PrintWriter
CharArrayReader InputStreamReader PushbackInputStream
CharArrayWriter LineNumberReader PushbaclReader
DataInputStream ObjectInputStream RandomAccessFile
DataOutputStream ObjectInputStream.GetField Reader
File ObjectOutputStream SequenceInputStream
FileDescriptor ObjectOutputStream.PutField SerializablePermission
FileInputStream ObjectStreamClass StreamTokenizer
FileOutputStream ObjectStreamField StringReader
FilePermission OutputStream StringWriter
FileReader OutputStreamWriter Writer

The Following interface are define by java.io


DataInput FileNameFilter ObjectOutput
DataOutput ObjectInput ObjectStreamConstants
Externalizable ObjectInputValidation Serializable
FileFilter

2
File and Random Access File Class
The File class is used to get the information of a file, such as the length of file,
its permissions, directory path etc.You can also create a directory , delete a file
and directory using the File class. The File class has many useful methods and
constants that can be used to get such kind of information about file. The File
class has following constructors.

1) File(String path)
2) File(String directoryPath,String filename)
3) File(File obj,String filename)

The Methods defined by the File class are given below.

1) String getName()
it returns the name of the file.
2) String getParent()
it returns the name of the parent Directory.
3) String getPath()
it returns the path of the file.
4) boolean canRead()
It returns true if the file exists and can be read,else returns false.
5) boolean canWrite()
It returns true if the file exists and can be Written,else returns false.
//Demonstrate File
import java.io.File;
class FileDemo
{
static void p(String s)
{
System.out.println(s);
}
}

class FileDemoMain
{
public static void main(String args[])
{
File f1 = new File("D:/RPBC/MRK_Java/Practicle/CH_3/Part-2/");
FileDemo.p("File Name :"+f1.getName());
FileDemo.p("Path :"+f1.getPath());
FileDemo.p("Abs Path :"+f1.getAbsolutePath());
FileDemo.p("Parent :"+f1.getParent());
3
FileDemo.p(f1.exists()?"exists":"is not exists");
FileDemo.p(f1.canWrite()?"is writeable":"is not writeable");
FileDemo.p(f1.canRead()?"is readable":"is not readable");
FileDemo.p("is"+(f1.isDirectory() ? "Yes": "not" + "a directory"));
FileDemo.p(f1.isAbsolute() ? "is normal file":"moght name piped");
FileDemo.p("File last modified :"+f1.lastModified());
FileDemo.p("File Size :"+f1.length() +"size");
}
}

4
RandomAccessFile:
RandomAccessFile class is used to read and write data from a file randomly.
This class is not a subclass of InputStream or OutputStream but it is directly the
subclass of Object class.This class implements DataInput and DataOutput
interfaces.
Its Constructors are:-

RandomAccessFile(File obj,String mode) throws IOException


RandomAccessFile(String filename,String mode) throws IOException

Some Methods of RandomAccessFile class are :-

1) void seek(long numOfBytes) throws IOException


It positions the file pointer after the numOfBytes bytes.
Now the Reading or writing of bytes is Done from this location.
This method is the most important method of RandomAccessFile as it
allows random access to a file.
2) int read()
it reads and returns a byte from the input stream.
3) long getFilePointer()
It returns the current position of the file pointer.
4) long length()
it returns the length of the file in bytes.

5
import java.io.*;
class RandomAccessFileDemo
{
public static void main(String[] args)
{
try
{
// create a new RandomAccessFile with filename test its
automatic creating
RandomAccessFile raf = new
RandomAccessFile("D:/RPBC/MRK_Java/Practicle/CH_3/Part-2/test.txt",
"rw");

// write something in the file


raf.writeUTF("Hello World");

// set the file pointer at 0 position


raf.seek(0);

// read and print the contents of the file


System.out.println("" + raf.readUTF());

// close the strea and release resources


System.out.println("Closing Stream...");
// set the file pointer at 4rth position
raf.seek(4);

// read the first byte and print it


System.out.println("" + raf.read());
raf.close();
System.out.println("Stream Closed.");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}

6
Reading and Writing Through Byte Stream Classes
The byte stream classes provide a rich environment for handling byte-oriented
I/O. A stream can be used with any type of object, including binary data. This
versatility makes byte streams important to many types of programs. Since the
byte stream classes are topped by InputStream and OutputStream, our
discussion will begin with them
InputStream
InputStream is an abstract class that defines java’s model of streaming byte
input. All of the method in this class will throw an IOException on error
condition.
Methods Defined by InputStream
Method Description
Int available() Return the number of bytes of input
currently
Void close() Closes the input source. Further read
attempts will generate an IOException
Void mark(int numBytes) Places mark at the current point in the
input stream that will remain valid
until numBytes bytes are read.
Boolean markSupported() Return true if mark()/reset() are
supported by the invoking stream
Int read() Returns an integer representation of the
available byte of input. -1 is return
when the end of the file is encountered.
Int read(byte buffer[]) Attempts to read up to buffer.length
bytes into buffer and returns the actual
number of bytes that were successfully
read. -1 is returned when the end of the
file is encountered
Int read(byte buffer[], int offset, int Attempts to read up to numbytes bytes
numByte) into buffer starting at buffer, returing
the number of bytes successfully read.
-1 is returned when the end of file is
encountered
Void reset() Resets the input pointer to the
previously
Long skip(long numBytes) Ignor(that is,skips) numBytes bytes of
input, returning the number of byte
actually ignored.

7
OutputStream
OutputStream is an abstract class that deinfes streaming byte output. All of the
method in the class return a void value and throw an IOException in the case of
error. Table shows the method in OutputStream.

Methods Defined by OutputStream


Method Description
void close() Closes the output stream. Further write
attempts will generate an IOException
void flush() Finalizes the output state so that any
buffers are cleared. That is, it flushes
the output buffers.
Void write(int b) write a single byte to an output stream.
Note that the parameter is an int, which
allows you to call write() with
expressions without having to cast
them.
void write(byte buffer[]) writes a complete array of bytes to an
output stream.
void write(byte buffer[], int offset, int writes a sub range of name nameBytes
numBytes) bytes from the array buffer, beginning
at buffer[offset]/

FileInputStream
The FileInputStream class creates an InputStream that can use to read bytes
from a file.
It two most common constructors are shown here:
FileInputStream(String filepath)
FileInputStream(File fileObject)
Either can throw a FileNotFoundExcetpion. Here, filepath is the fill path name
of a file, and fileObj is a File object that describes the file.
The following example creates two FileInputStream that use the same disk file
and each of the two constructors.
FileInputStream fis = new FileInputStream(“/autoexces.bat”);
File f = new File(“/autoexec.bat”);
FileInputStream f1 = new FileInputStream(f);

Method Of FileInputStream
Method Description
int available() It is used to return the estimated number of bytes that can be
read from the input stream.
int read() It is used to read the byte of data from the input stream.

8
int read(byte[] It is used to read up to b.length bytes of data from the input
b) stream.
int read(byte[] It is used to read up to len bytes of data from the input stream.
b, int off, int
len)
long skip(long It is used to skip over and discards x bytes of data from the
x) input
stream.
FileChannel It is used to return the unique FileChannel object associated
getChannel() with the file input stream.
FileDescriptor It is used to return the FileDescriptor object.
getFD()
protected void It is used to ensure that the close method is call when there is
finalize() no more reference to the file input stream.
void close() It is used to closes the stream.

//Demonstrate FileInputStream.
import java.io.*;
class FileInputStreamEx
{
public static void main(String arg[])
{
try
{
File file = new File(arg[0]);
FileInputStream f = new FileInputStream(file);
System.out.println("The Contents of the file:");
int ch;
do
{
ch = f.read();
if(ch!=-1)
System.out.print((char)ch);
}while(ch!=-1);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("File not Found");}
catch(FileNotFoundException e){
System.out.println("File not Found");}
catch(IOException e){
System.out.println("IO Exception Generated");
}
}
}
9
FileOutputStream
The FileOutputStream class create an OutputStream that you can use to write
bytes from a file. Its two most common constructors are show here:
FileOutputStream(String filePath);
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
They can throw a FileNotFoundException or a SecurityException. Here,
filePath is the fill path name of a file, and fileObj is a file object that describes
the file. If append is true, the file opened in append mode.
Creation of FileOutputStream is not dependent on the file already existing.
FileOutputStream will create the file before opening it for output when you
create the object. In the case where you attempt to open a read-only file, an
IOException will be thrown.
Method of FileOutputStream
Method Description
protected void finalize() It is sued to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to
the file output stream.
void write(byte[] ary, int It is used to write len bytes from the byte array starting at
off, int len) offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
FileChannel getChannel() It is used to return the file channel object associated with
the file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the
stream.
void close() It is used to closes the file output stream.

//Demonstrate FilOutputStream
import java.io.*;
class FileOutputStreamEx
{
public static void main(String arg[])
{
try{
FileOutputStream f = new FileOutputStream("test.txt",true);
//Append Mode
byte buffer[]={97,98,99,100}; //ASCII values of a to d
f.write(buffer);

10
for(int i=65;i<=70;i++) //ASCII values of A to F
{ f.write(i);
}
f.close();
}
catch(IOException e)
{
System.out.println("IO exception Occurred");
}
System.out.println("Data Written in the file");
}
}

BufferedInputStream
Buffering I/O is a very common performance optimization. Java’s
BufferedInputStream class allows to “wrap” any InputStream into a buffered
stream and achieve this performance improvement.
BufferedInputStream has two constructors:
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)

The first form creates a buffered stream using a default buffer size.
In the second, the size of the buffer is passed in bufSize. Use of sizes that are
multiples of memory pages, disk block, and so on can have a significant positive
impact on performance.

//Use Buffered input


import java.io.*;
class BufferedInputStreamEx
{
public static void main(String arg[])
{
try
{
FileInputStream f = new FileInputStream("test.txt");
BufferedInputStream b = new BufferedInputStream(f);
System.out.println("the contents of the file");
int ch;
do
{
ch=b.read();
if(ch!=-1)
System.out.print((char)ch);
}while(ch!=-1);
11
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found");
}
catch(IOException e)
{
System.out.println("IO Exception generated");
}

}
}

BufferedOutputStream
A BufferedOutputStream is similer to any OutputStream with the exception
of added flush( ) method that is used to ensure that data buffers are physically
written to the actual output device.
Since the point of a BufferedOutputStream is to improve performance by
reducing the number of times the system actually writes data, you may need to
call flush( ) to cause any data that is in the buffer to get written.
Unlike buffered input, buffering output does not provide additional functionality.
Buffers for output in java are there to increase performance. Here are the two
available constructors.
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int size)
The first form creates a buffered stream using a buffer of 512 bytes. In the
second form, the size of the buffer is passed in bufsize.

12
import java.io.*;
class BufferedOutputStreamDemo
{
public static void main(String args[])throws Exception
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to RPBC College.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
DataOutputStream
data output stream lets an application write primitive Java data types to an output
stream in a portable way. An application can then use a data input stream to read
the data back in.
Constructor and Description :
 DataOutputStream (OutputStream out) : Creates a new data output
stream to write data to the specified underlying output stream.

Method of DataOutputStream
int size() It is used to return the number of bytes written to the
data output stream.
void write(int b) It is used to write the specified byte to the underlying
output stream.
void write(byte[] b, int off, It is used to write len bytes of data to the output
int len) stream.
void writeBoolean(boolean It is used to write Boolean to the output stream as a 1-
v) byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte
value.
void writeChars(String s) It is used to write string to the output stream as a
sequence of characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-
byte value.

13
void writeBytes(String s) It is used to write string to the output stream as a
sequence of bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using
UTF-8 encoding in portable manner.
void flush() It is used to flushes the data output stream.
import java.io.*;
public class DataOutputStreamDemo
{
public static void main(String[] args) throws IOException
{
FileOutputStream file = new FileOutputStream("DataOutputStream.txt");
DataOutputStream data = new DataOutputStream(file);

for(int i=65;i<=96;i++)
{
data.writeInt(i);
}
data.flush();
data.close();
System.out.println("Succcess...");
}
}

14
DataInputStream
A data input stream enable an application read primitive Java data types from an
underlying input stream in a machine-independent way(instead of raw bytes).
That is why it is called DataInputStream – because it reads data (numbers)
instead of just bytes.

An application uses a data output stream to write data that can later be read by a
data input stream. Data input streams and data output streams represent Unicode
strings in a format that is a slight modification of UTF-8.
DataInputStream is not necessarily safe for multithreaded access. Thread safety
is optional and is the responsibility of users of methods in this class.

Constructor:
DataInputStream(InputStream in) : Creates a DataInputStream that uses the
specified underlying InputStream.

Method of DataInputStream
Method Description
int read(byte[] b) It is used to read the number of bytes from the input
stream.
int read(byte[] b, int off, int It is used to read len bytes of data from the input
len) stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char
value.
double readDouble() It is used to read eight input bytes and returns a double
value.
boolean readBoolean() It is used to read one input byte and return true if byte is
non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input
stream.
String readUTF() It is used to read a string that has been encoded using
the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and store
them into the buffer array.
void readFully(byte[] b, int It is used to read len bytes from the input stream.
off, int len)

15
import java.io.*;
class DataOutputStreamEx
{
public static void main(String arg[])
{
try
{
FileOutputStream f = new FileOutputStream("file4.txt");
DataOutputStream d = new DataOutputStream(f);
d.write(123);
d.writeBoolean(true);
d.writeUTF("Hello BCA 4 Students");
f.close();
}
catch(IOException e)
{
System.out.println("IO Exception");
}
}
}
Second Program
import java.io.*;
//First Execute DataOutputStream class than after execute DataInputStream class
class DataInputStreamEx
{
public static void main(String arg[])
{
try
{
FileInputStream f = new FileInputStream("file4.txt");
DataInputStream d = new DataInputStream(f);
System.out.println("The Contents of File4 are");
System.out.println(d.read());
System.out.println(d.readBoolean());
System.out.println(d.readUTF());
f.close();
}
catch(IOException e)
{
System.out.println("IO Exception");
}
}
}

16
Reading and Writing through Character Stream classes
While the byte stream classes provide sufficient functionality to handle any type
of I/O operation, they cannot work directly with Unicode characters.
Since one of the main purposes of java is to support the “write once, run
anywhere” philosophy, it was necessary to include direct I/O support for
character.
In this section, several of the character I/O classes are discussed.
As explained earlier, at the top of the character stream hierarchies are the
Reader and Writer abstract classes. We will begin with them.

Reader
Reader is an abstract class that define Java’s model of streaming character
input. All of the method in this class return an IOException on error condition.

Writer
Writer is an abstract class that define streaming character output. All of
the methods in this class return a void value and through IOException in the
case of errors.

FileWriter
FileWriter creates a Writer that you can use to write to a file. Its most
commonly used constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, booleanAppend)
FileWriter(File fileObj)
They can throw an IOException. Here, filePath is the full path name of a file,
and fileObj is a File object that describes the file. If append is true, then output
is appended to the end of the file.
Creation of FileWriter is not depended on the file already existing. FileWriter
will create the file before opening if for output when you create the object. In the
case where you attempt to open a read-only file, an IOException will be thrown.

17
Method defined by Writer
Method Description
Abstract void close( ) Closes the output tream. Further write
attempt will generate an IOException.
Abstreact void flush( ) Finalizes the output state so that any
buffers are cleared. That is, it flushes
the output buffers.
Void write(int ch) Writes a single character to the
invoking output stream. Note that the
parameter is an int, which allows you
to call write with expressions without
having to cast them back to char.
Void write(char buffer[]) Writes a complete array of character to
the invoking output stream.
Abstreact void write(char buffer[], int Writes a subrange of numChars
offset, int numChars) characters from the array buffer,
beginning at biffer[offset] to the
invoking output stream.
Void write(String str) Writes str to the invoking output
stream.
Void write(String str, int offset, int Writes a subrange of numChars
numChars) characters from the array str, beginning
at the specified offset.

18
FileReader
The FileReader class creates a Reader that you can use to read the contents of
file. Its two most commonly used constructors are shown here.
FileReader(String filePath)
FileReader(File fileObj)

The Methods Defined by Reader


Method Description
abstract void close( ) Closes the input source. Futher read
attempts will generate an IOException.
void mark(int numChars) places a mark at the current point in the
input stream that will remain valid
until numChars characters are read.
boolean makrSupported( ) returns true if mark()/reset() are
supported on this stream.
int read( ) returns an integer representation of the
next available character from the
invoking input stream. -1 is returned
when the end of the file is encountered
int read(char buffer[ ] ) 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 encountered.
abstract int read( char buffer[ ], int attempts to read up to numChars
offset, int numChars) characters into buffer starting at
buffer[offset], returning the number of
characters successfully read. -1 is
returned when the end of the file is
encountered.
boolean ready( ) returns true if the next input request
will not wait. Otherwise, it return false.
void reset( ) resets the input pointer to the
previously set mark.
long skip(long numChars) skips over numChars characters of
input, returning the number of
characters actually skipped.
Either can throw a FileNotFoundException. Here, filePath is the Full path name
of a file, and fileObj is a File object that describes the file.

19
Buffered Character Stream
This section describes how you can buffer input and output for character stream.
The following classes are outline: BufferedWriter and BufferedReader.
The advantage of buffering is that the number of reads and writes to a physical
device is reduced. This improves perforamce.

BufferedWriter
The BufferedWriter class extends Writer and buffers output to a character
stream. Its constructors are as follows:
BufferedWriter(Writer w)
BufferedWriter(Writer w, int bufSize)
The first form creates a buffered stream using a buffer with a default size. In the
second, the size of the buffers is specified by bufSize.
This class implements all of the methods define by Writer. In addition, it
provides the newLine( ) method to output a line separator. Its signature is shows
below:
Void newLine( ) throws IOException
Example of BufferdWriter
//Demonstrate BufferdWrite
import java.io.*;
class BufferedWriterDemo
{
public static void main(String args[])
{
try
{
//Create a file write
FileWriter fw= new FileWriter(args[0]);

//Create strings buffered writer


BufferedWriter bwf = new BufferedWriter(fw);

//write a string to the file


for(int i =0; i<25;i++)
{
bwf.write("Line"+i+"\n");
}
bwf.close();
}
catch(Exception e)
{
System.out.println("The Exception:"+e);
}
20
}
}

21
Buffered Reader
The BufferedReader class extends Reader and buffered input form a character
stream. Its constructors are as follows:
BufferedReader(Reader r)
BufferedReader(Reader r, int bufSize)
The first form creates a buffered stream using a buffer with a default size. In the
seconds, the size of the buffer specified by bufSize.
This class implements all of the functionality defined by Reader. In addition, the
readLine( ) methods reads new line-terminated strings from a character stream.
Its signature is
String readLine() throws IOException

Example of BufferedReader
//demonstrate Bufferd Reader
import java.io.*;
class BufferedReaderDemo
{
public static void main(String args[])
{
try{
//create a file reader
FileReader fr = new FileReader(args[0]);
//create a bufferd reader
BufferedReader bf = new BufferedReader(fr);

//read and display lines from file


String s;
while((s = bf.readLine()) != null)
{
System.out.println(s);
}
fr.close();
}
catch(Exception e){
System.out.println("The Exception :"+e);
}
}
}

22
StreamTokenizerClass
The StreamTokenizer class parses the data from a character input stream and
generates a sequence of tokens. Tokens is a group of character that represent a
number or word. This functionality can be very valuable if you need to build
parsers, compilers, or any program that processes character input. A constructor
for this class is as follows.
StreamTokenizer(Reader r)
Here, r is a reader
The class defines four consants. TT_EOF menace end_of_file and TT_EOL
menace end-of-line conditions, respectively. TT_NUMBER and TT_WORD
indicate that a number of words have been read.
Three instance variables provide valuable information. If the current token is a
number, nval contains value and ttype equals TT_NUMBER. If the current
token is a string, sval contains its value and ttype equals TT_WORD.
Otherwise, ttytpe contains the character that has been read.
Method of StreamTokenizer class:
Method Description
void commentChar(int ch) Specified that the character argument starts a
single-line comment.
void eolIsSignificant(boolean This method determines whether or not ends
flag) of line are treated as tokens.
int lineno() This method returns the current line number.
void lowerCaseMode(boolean fl) This method determines whether or not word
token are automatically lowercased.
int nextToken() This method parses the next token from the
input stream of this tokenizer.
void ordinaryChar(int ch) This method specifies that the character
argument is "ordinary" in this tokenizer.
void ordinaryChars(int low, int This method specifies that all characters c in
hi) the range low <= c <= high are "ordinary" in
this tokenizer.
void parseNumbers() This method specifies that numbers should
be parsed by this tokenizer.
void pushBack() This method causes the next call to the
nextToken method of this tokenizer to return
the current value in the ttype field, and not to
modify the value in the nval or sval field.
void quoteChar(int ch) This method specifies that matching pairs of
this character delimit string constants in this
tokenizer.
void resetSyntax() This method resets this tokenizer's syntax
table so that all characters are "ordinary." See
the ordinaryChar method for more

23
information on a character being ordinary.
void This method determines whether or not the
slashSlashComments(boolean tokenizer recognizes C++ style comments.
flag)
void slashStarComments(boolean This method determines whether or not the
flag) tokenizer recognizes C style comments.
String toString() This method returns the string representation
of the current stream token and the line
number it occurs on.
void wordChars(int low, int hi) This method specifies that all characters c in
the range low <= c >= high are word
constituents.
Example:
//Streamtokenizer classpublic class STDemo
import java.io.*;
class StreamTokenizerDemo
{
public static void main(String args[]) throws IOException
{
//First Create the rpbc.txt file and write some contents..
FileReader freader = new FileReader("rpbc.txt");
StreamTokenizer st = new StreamTokenizer(freader);

double sum = 0;
int numWords = 0, numChars = 0;
while(st.nextToken() != st.TT_EOF)
{
if(st.ttype == StreamTokenizer.TT_NUMBER)
{
sum += st.nval;
}
else if(st.ttype == StreamTokenizer.TT_WORD)
{
numWords++;
numChars += st.sval.length();
}
}
System.out.println("Sum of total numbers in the file: " + sum);
System.out.println("Total words (does not include numbers) in the
file: " + numWords);
System.out.println("No. of characters available in words: " +
numChars);
}
}
24
PipedStream
PipedInputStream and PipedOutputStream classes

The PipedInputStream and PipedOutputStream classes can be used to read and


write data simultaneously. Both streams are connected with each other using the
connect() method of the PipedOutputStream class.

PipedInputStream
The Java.io.PipedInputStream class is a piped input stream that can be
connected to a piped output stream, the piped input stream then provides
whatever data bytes are written to the piped output stream.Following are the
important points about PipedInputStream −
 The piped input stream contains a buffer, decoupling read operations from
write operations, within limits.
 Attempting to use both objects from a single thread is not recommended,
as it may deadlock the thread.
 A pipe is said to be broken if a thread that was providing data bytes to the
connected piped output stream is no longer alive.
Class constructors
Constructor & Description
PipedInputStream()

This creates a PipedInputStream so that it is not yet connected.


PipedInputStream(int pipeSize)

This creates a PipedInputStream so that it is not yet connected and uses the specified
pipe size for the pipe's buffer.
PipedInputStream(PipedOutputStream src)

This creates a PipedInputStream so that it is connected to the piped output stream src.
PipedInputStream(PipedOutputStream src, int pipeSize)

This creates a PipedInputStream so that it is connected to the piped output


stream src and uses the specified pipe size for the pipe's buffer.
Class methods
Method & Description
int available()

This method returns the number of bytes that can be read from this input stream
without blocking.
25
void close()

This method closes this piped input stream and releases any system resources
associated with the stream.
void connect(PipedOutputStream src)

This method causes this piped input stream to be connected to the piped output
stream src.
int read()

This method reads the next byte of data from this piped input stream.
int read(byte[] b, int off, int len)

This method reads up to len bytes of data from this piped input stream into an array of
bytes.
protected void receive(int b)

This method receives a byte of data.

PipedOutputStream

The Java.io.PipedOutputStream class is a piped output stream that can be


connected to a piped input stream to create a communications pipe.Following
are the important points about PipedOutputStream −

 The piped output stream is the sending end of the pipe.


 Attempting to use both objects from a single thread is not recommended
as it may deadlock the thread.
 Data is written to a PipedOutputStream object by one thread and data is
read from the connected PipedInputStream by some other thread.
 The pipe is said to be broken if a thread that was reading data bytes from
the connected piped input stream is no longer alive.
Class constructors
S.N. Constructor & Description

1 PipedOutputStream()

This creates a piped output stream that is not yet connected to a piped input
stream.
2 PipedOutputStream(PipedInputStream snk)

This creates a piped output stream connected to the specified piped input
stream.

26
Class methods
Method & Description

void close()

This method closes this piped output stream and releases any system resources
associated with this stream.
void connect(PipedInputStream snk)

This method connects this piped output stream to a receiver.


void flush()

This method flushes this output stream and forces any buffered output bytes to be
written out.
void write(byte[] b, int off, int len)

This method writes len bytes from the specified byte array starting at offset off to this
piped output stream.
void write(int b)

This method writes the specified byte to the piped output stream.

import java.io.*;
class PipedWR
{
public static void main(String args[])throws Exception
{
final PipedOutputStream pout=new PipedOutputStream();
final PipedInputStream pin=new PipedInputStream();

pout.connect(pin);//connecting the streams

//creating one thread t1 which writes the data


Thread t1=new Thread()
{
public void run()
{
for(int i=65;i<=90;i++)
{
try
{
pout.write(i);
Thread.sleep(1000);
}
27
catch(Exception e)
{}
}
}
};

//creating another thread t2 which reads the data


Thread t2=new Thread()
{
public void run()
{
try
{
for(int i=65;i<=90;i++)
{
System.out.println(pin.read());
}
}
catch(Exception e){}
}
};
//starting both threads
t1.start();
t2.start();
}
}

28
Serialization in Java

Serialization in java is a mechanism of writing the state of an object into a byte


stream.

It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization.

Advantage of Java Serialization

It is mainly used to travel object's state on the network (known as marshaling).

java.io.Serializable interface

Serializable is a marker interface (has no data member and method). It is used to


"mark" java classes so that objects of these classes may get certain capability.
The Cloneable and Remote are also marker interfaces.

It must be implemented by the class whose object you want to persist.

The String class and all the wrapper classes


implements java.io.Serializable interface by default.

//Object Outputstream class

import java.io.Serializable;

public class Student implements Serializable

int id;

String name;
29
public Student(int id, String name)

this.id = id;

this.name = name;

ObjectOutputStream
ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types and Java
objects to an OutputStream. Only objects that support the java.io.Serializable
interface can be written to streams.

Constructor
1) public ObjectOutputStream(OutputStream out) throws IOException {}creates an
ObjectOutputStream that writes to the specified OutputStream.
Important Methods
Method Description
1) public final void writes the specified object to the
writeObject(Object obj) throws ObjectOutputStream.
IOException {}
2) public void flush() throws flushes the current output stream.
IOException {}
3) public void close() throws closes the current output stream.
IOException {}
import java.io.*;
class ObjectOututStreamDemo
{
public static void main(String args[])throws Exception
{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);

out.writeObject(s1);
out.flush();
System.out.println("success");
}
30
}

31
Deserialization in java

Deserialization is the process of reconstructing the object from the serialized


state.It is the reverse operation of serialization.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an


ObjectOutputStream.

Constructor
1) public ObjectInputStream(InputStream creates an ObjectInputStream that
in) throws IOException {} reads from the specified
InputStream.
Important Methods
Method Description
1) public final Object readObject() reads an object from the input stream.
throws IOException,
ClassNotFoundException{}
2) public void close() throws closes ObjectInputStream.
IOException {}
import java.io.*;
class ObjectInputStreamDemo
{
public static void main(String args[])throws Exception
{

ObjectInputStream in=new ObjectInputStream(new


FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
in.close();
}
}

32
InputStreamReader
The Java.io.InputStreamReader class is a bridge from byte streams to
character streams.It reads bytes and decodes them into characters using a
specified charset.
Class constructors
Constructor & Description

InputStreamReader(InputStream in)

This creates an InputStreamReader that uses the default charset.


InputStreamReader(InputStream in, Charset cs)

This creates an InputStreamReader that uses the given charset.


InputStreamReader(InputStream in, CharsetDecoder dec)

This creates an InputStreamReader that uses the given charset decoder.


InputStreamReader(InputStream in, String charsetName)

This creates an InputStreamReader that uses the named charset.


Class methods
Method & Description
void close()

This method closes the stream and releases any system resources associated with it.
String getEncoding()

This method returns the name of the character encoding being used by this stream.
int read()

This method reads a single character.


int read(char[] cbuf, int offset, int length)

This method reads characters into a portion of an array.


boolean ready()

This method tells whether this stream is ready to be read.


import java.io.*;
class InputStreamReaderEx
{
public static void main(String arg[])throws IOException
{
InputStreamReader i = new InputStreamReader(System.in);
33
BufferedReader b = new BufferedReader(i);
System.out.println("Enter the num 1:");
Double n1= new Double(b.readLine());
System.out.println("Enter the num2:");
Double n2= new Double(b.readLine());
double sum=n1+n2;
double mul=n1*n2;
System.out.println("The Sum is:="+sum);
System.out.println("The Multiplication is:="+mul);
}
}

OutputStreamWriter

The Java.io.OutputStreamWriter class is a bridge from character streams to


byte streams. Characters written to it are encoded into bytes using a specified
charset.

Class constructors
S.N. Constructor & Description

1 OutputStreamWriter(OutputStream out)

This creates an OutputStreamWriter that uses the default character encoding.

2 OutputStreamWriter(OutputStream out, Charset cs)

This creates an OutputStreamWriter that uses the given charset.


3 OutputStreamWriter(OutputStream out, CharsetEncoder enc)

This creates an OutputStreamWriter that uses the given charset encoder.


4 OutputStreamWriter(OutputStream out, String charsetName)

This creates an OutputStreamWriter that uses the named charset.


Class methods
Method & Description

void close()

This method closes the stream, flushing it first.


void flush()

This method flushes the stream.

34
String getEncoding()

This method returns the name of the character encoding being used by this stream.
void write(char[] cbuf, int off, int len)

This method writes a portion of an array of characters.


void write(int c)

This method writes a single character.


void write(String str, int off, int len)

This method writes a portion of a string.


import java.io.*;

class OutputStreamWriterDemo
{

public static void main(String[] args)


{
char[] arr = {'H', 'e', 'l', 'l', 'o'};
try
{

// create a new OutputStreamWriter


OutputStream os = new FileOutputStream("test.txt");
OutputStreamWriter writer = new OutputStreamWriter(os);

// create a new FileInputStream to read what we write


FileInputStream in = new FileInputStream("test.txt");

// write something in the file


writer.write(arr, 0, 3);

// flush the stream


writer.flush();

// read what we write


for (int i = 0; i < 3; i++)
{
System.out.print("" + (char) in.read());
}

}
catch (Exception ex)
35
{
ex.printStackTrace();
}
}
}

36

You might also like