0% found this document useful (0 votes)
1 views116 pages

3_Java IO_Files_Streams and Object Serialization

The document covers Java GUI and file streams, detailing predefined libraries, string handling, Java I/O, and the use of AWT and Swing. It explains the concepts of input and output streams, including byte and character streams, along with specific classes like FileInputStream and FileOutputStream for file operations. Additionally, it includes examples of reading from and writing to files, as well as using ByteArrayInputStream and ByteArrayOutputStream.

Uploaded by

samkumaran005
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)
1 views116 pages

3_Java IO_Files_Streams and Object Serialization

The document covers Java GUI and file streams, detailing predefined libraries, string handling, Java I/O, and the use of AWT and Swing. It explains the concepts of input and output streams, including byte and character streams, along with specific classes like FileInputStream and FileOutputStream for file operations. Additionally, it includes examples of reading from and writing to files, as well as using ByteArrayInputStream and ByteArrayOutputStream.

Uploaded by

samkumaran005
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/ 116

UNIT II – JAVA GUI AND FILE

STREAMS
 Predefined Libraries
 Using String class
 Working with Data & Time
 Utility framework
 Java I/O
 AWT & Swings
 Regular Expressions
 Files, Streams and Object Serialization
 Generic collections – Generic Classes and Methods
 Java Applet Basics- Graphics and Animation in Applet- Event
Handling and Applet Communication
 Reflections in Java

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 1
CAMPUS ANNA UNIVERSITY
Java I/O,
Files, Streams and Object
Serialization

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 2
CAMPUS ANNA UNIVERSITY
Streams
• A stream is a sequence of data of undetermined
length.
• Java uses the concept of stream to make I/O
operation fast.
• The java.io package contains all the classes
required for input and output operations.
• In java, 3 streams are created for us automatically.
All these streams are attached with console.
 System.out: standard output stream
 System.in: standard input stream
 System.err: standard error stream
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 3
CAMPUS ANNA UNIVERSITY
OutputStream vs InputStream

• InputStream
Java application uses an input stream to read data from a
source, it may be a file, an array, peripheral device or
socket.
• OutputStream
Java application uses an output stream to write data to a
destination, it may be a file, an array, peripheral device or
socket.
28-Aug-25
BVL_DR.KALAM COMPUTING CENTRE, MIT
4
CAMPUS ANNA UNIVERSITY
IO Stream
• Java defines two types of streams. They are,
Byte Stream : It provides a convenient means for
handling input and output of byte.
Character Stream : It provides a convenient
means for handling input and output of
characters.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 5
CAMPUS ANNA UNIVERSITY
ByteArrayInputStream LineNumberInputStream
File FileInputStream BufferedInputStream
FilterInputStream DataInputStream
InputStream SequenceInputStream PushbackInputStream
StringBufferInputStream

PipedInputStream

Object ObjectInputStream

ByteArrayOutputStream

OutputStream FileOutputStream
BufferedOutput
Stream
FilterOutputStream
Reader DataOutputStream
PipedOutputStream

ObjectOutputStream PrintStream
Writer
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 6
CAMPUS ANNA UNIVERSITY
FileStreams
• FileInputStream Class
This class obtains input bytes from a file.
 It is used for reading byte-oriented data (streams of
raw bytes) such as image data, audio, video etc.
We can also read character-stream data. But, for
reading streams of characters, it is recommended to
use FileReader class.
• Constructors
1. InputStream f = new FileInputStream("C:/java/hello");
2. File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 7
CAMPUS ANNA UNIVERSITY
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.
int read(byte[] b) It is used to read up to b.length bytes of data
from the input stream.
int read(byte[] b, It is used to read up to len bytes of data from
int off, int len) the input stream starting at offset off
long skip(long x) It is used to skip over and discards x bytes of
data from the input stream.
FileChannel It is used to return the unique FileChannel object
getChannel() associated 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
finalize() when there is no more reference to the file input
stream.
BVL_DR.KALAM COMPUTING CENTRE, MIT
void close()
28-Aug-25
It is used to closes the stream.
CAMPUS ANNA UNIVERSITY
8
Program to Read data from a file ( using throws)
// 1. Import package
// 2. Handle Exception

// 3. Create InputStream
Object to READ from file
// 4.Dynamically Read from the file

// 5. Close the Inputstream

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 9
CAMPUS ANNA UNIVERSITY
Program to Read data from a file ( using try catch)
//Read the content from already existing file and show in the screen
import java.io.*;
class FileReadingEx1
{ test.txt
public static void main(String a[]) java is an object oriented programming
{ language
try
{
int i=0;
FileInputStream fin=new FileInputStream("test.txt");
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
fin.close();
}catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 10
CAMPUS ANNA UNIVERSITY
FileStreams
• FileOutputStream Class
This is an output stream used for writing data to a file.
It can be used to write primitive values and byte
oriented data into a file
It can be used for character-oriented data .But, it is
preferred to use FileWriter than FileOutputStream.
• Constructors
1.OutputStream f = new FileOutputStream("C:/java/hello“)
2.File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 11
CAMPUS ANNA UNIVERSITY
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, It is used to write len bytes from the
int off, int len) byte array starting at 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 It is used to return the file channel object
getChannel() 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.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 12
CAMPUS ANNA UNIVERSITY
Program to write into a file ( using throws)

// 1. Import package
// 2. Handle Exception

// 3. Create OutputStream
Object to WRITE into file
// 4. Write into a file (byte content)

// 5. Close the Outputstream

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 13
CAMPUS ANNA UNIVERSITY
import java.util.Scanner;
import java.io.*; Writing to a file Example
class FileWritingEx1 //Get input from the user through
{
keyboard an write into a file
public static void main(String a[])
{
try
{
byte b[]=new byte[100];
char ch;
int i=0;
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader bs=new BufferedReader(in);
FileOutputStream fop=new FileOutputStream(“abc.txt");
System.out.println("Enter text you want to write in a file and end with # symbol:");
while((ch=(char)bs.read())!='#')
{
b[i]=(byte)ch;
i++;
}
fop.write(b);
System.out.println("Successfully written in file...");
fop.close();
BVL_DR.KALAM COMPUTING CENTRE, MIT
} 28-Aug-25 CAMPUS ANNA UNIVERSITY
14
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 15
CAMPUS ANNA UNIVERSITY
Writing and Reading in a file example
//Convert a String data to byte data
and write into a file and from that file
read the data show in the screen

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 16
CAMPUS ANNA UNIVERSITY
Copying One file to another

// Source file
// Destination file

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 17
CAMPUS ANNA UNIVERSITY
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 18
CAMPUS ANNA UNIVERSITY
Appending to a file

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 19
CAMPUS ANNA UNIVERSITY
ByteArrayStream
• This Stream contains,
ByteArrayInputStream
ByteArrayOutputStream
• ByteArrayInputStream Class
It can be used to read byte array as input stream.
• Constructor
1. ByteArrayInputStream(byte [] a)
This constructor accepts a byte array as a
parameter.
2.ByteArrayInputStream(byte [] a, int off, int len)
This constructor takes an array of bytes, and two
integer values, where off is the first byte to be read
and len is the number of bytes to be read.
28-Aug-25
BVL_DR.KALAM COMPUTING CENTRE, MIT
20
CAMPUS ANNA UNIVERSITY
Methods Description
int available() It is used to return the number of remaining
bytes that can be read from the input stream.

int read() It is used to read the next byte of data from


the input stream.
int read(byte[] ary, It is used to read up to len bytes of data from
int off, int len) an array of bytes in the input stream.
boolean It is used to test the input stream for mark and
markSupported() reset method.
long skip(long x) It is used to skip the x bytes of input from the
input stream.
void mark(int It is used to set the current marked position in
readAheadLimit) the stream.
void reset() It is used to reset the buffer of a byte array.
void close() It is used for closing a ByteArrayInputStream.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 21
CAMPUS ANNA UNIVERSITY
ByteArrayStream
ByteArrayOutputStream
• It creates a buffer in memory and all the data sent to the
stream is stored in the buffer.
• The buffer of ByteArrayOutputStream automatically grows
according to data.
• In this stream, the data is written into a byte array which can
be written to multiple streams later.
• Constructor
1. ByteArrayOutputStream() - Creates a new byte array output
stream with the initial capacity of 32 bytes, though its size
increases if necessary.
2. ByteArrayOutputStream(int size) - Creates a new byte array
output stream, with a buffer capacity of the specified size, in
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 22
bytes. CAMPUS ANNA UNIVERSITY
Method Description
int size() It is used to returns the current size of a buffer.
byte[] toByteArray() It is used to create a newly allocated byte array.
String toString() It is used for converting the content into a string
decoding bytes using a platform default
character set.
String toString(String It is used for converting the content into a string
charsetName) decoding bytes using a specified charsetName.
void write(int b) It is used for writing the byte specified to the
byte array output stream.
void write(byte[] b, It is used for writing len bytes from specified
int off, int len byte array starting from the offset off to the
byte array output stream.
void It is used for writing the complete content of a
writeTo(OutputStrea byte array output stream to the specified output
m out) stream.
void reset() It is used to reset the count field of a byte array
output stream to zero value.
void close() It is used to close the ByteArrayOutputStream.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 23
CAMPUS ANNA UNIVERSITY
ByteArrayInputStreamExample

import java.io.*;

public class ByteArrayInputStreamExample


{
public static void main(String[] args)
{
try
{
String str = "Welcome to MIT";

//get bytes from string using getBytes method


byte[] bytes = str.getBytes();

//create ByteArrayInputStream object


ByteArrayInputStream bip1 = new ByteArrayInputStream(bytes);
ByteArrayInputStream bip2 = new ByteArrayInputStream(bytes,4,6);

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 24
CAMPUS ANNA UNIVERSITY
int ch, i;
System.out.println("First output:");
//read bytes from ByteArrayInputStream using read method
while((ch = bip1.read()) != -1)
{
System.out.print((char)ch);
}

System.out.println("\nsecond output:");
while((i=bip2.available())>0)
{
ch = bip2.read();
System.out.print(Character.toUpperCase((char)ch));
}
}catch(Exception e)
{
System.out.print("Exception:"+e);
}
}
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 25
CAMPUS ANNA UNIVERSITY
import java.io.*; ByteArrayOutputStreamExample
public class ByteArrayOutputStreamExample
{
public static void main(String[] args)
{
try
{
ByteArrayOutputStream bop = new ByteArrayOutputStream();
System.out.println("Type a text and stop with full stop");
char ch;
while((ch=(char)System.in.read())!='.')
{
bop.write(ch);
}
byte b[]=bop.toByteArray();
for(int l=0;l<b.length;l++)
System.out.print((char)b[l]);
}catch(Exception e)
{
System.out.print("Exception:"+e);
}
}
} BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 26
CAMPUS ANNA UNIVERSITY
ByteArrayOutputStreamExample2

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 27
CAMPUS ANNA UNIVERSITY
FilterStreams
Object

InputStream
abstract

FilterInputStream

DataInputStream PushbackInputStream

LineNumberInputStream BufferedInputStream
All 4 subclasses of FilterInputStream are called high –level Streams and
remaining are called low level streams
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 28
CAMPUS ANNA UNIVERSITY
FilterStreams
Object

OutputStream
abstract

FilterOutputStream

DataOutputStream
PrintStream

BufferedOutputStream
All 3 subclasses of FilterOutputStream are called high –level Streams
and remaining are called low level streams
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 29
CAMPUS ANNA UNIVERSITY
FilterStreams
• FilterStreams can be linked to another to have high
functionality, but subject to some rules.
• The job of high level streams is to add extra functionality to
the existing streams.
 Ex. LineNumberInputStream adds line numbers in the destination
file that do not exist in source file.
 DataInputStream increases performance with readInt() and
readLine() methods.
• For high functionality, one stream can be linked or
chained to another, but obeying some rules.
• Chaining is very simple.
• The output of one stream becomes input to the other
(or) pass an object of one stream as parameter to
another stream constructor
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 30
CAMPUS ANNA UNIVERSITY
Rules of chaining
1. The input for a high level stream may come from a low-level stream
or another high level stream
i.e.. In programming, the constructor of high level stream can be
passed with an object of low-level (or) high-level.
2. Being low-level, the low level stream should work by itself. if not
entitled to get passes with any other stream
In programming, the low level streams opens the file and hand it over
(passes) to a high level stream .
High level stream cannot open a file directly
High level streams just add extra functionality and depend solely on
low-level streams
String str=“welcome to mit”
Low level
StringBufferInputStream sbi=new StringBufferInputStream(str);
LineNumberInputStream lis=new LineNumberInputStream(sbi);
DataInputStream ds=new DataInputStream(lis);
28-Aug-25 BVL_DR.KALAM COMPUTING CENTRE, MIT 31
CAMPUS ANNA UNIVERSITY high level high level
DataInputStream & DataOutputStream
• These are high-level classes as they are sub classes of
FilterInputStream and FilterOutputStream
• These streams extra functionality is that they can read
(or) write primitive Java data types (integers, doubles
)from an underlying input stream in a machine-
independent way, instead of byte by byte,
• This increases the performance to some extend, instead of
reading & writing byte by byte.
• DataInputStream is not necessarily safe for
multithreaded access

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 32
CAMPUS ANNA UNIVERSITY
DataInputStream constructor
• DataInputStream(InputStream in)
This creates a DataInputStream that uses the specified
underlying InputStream.
Method & Description
int read(byte[] b) This method reads some number of
bytes from the contained input stream and stores them into the
buffer array b
int read(byte[] b, int off, int len)  This method reads up
to len bytes of data from the contained input stream into an array
of bytes.
boolean readBoolean() This method reads one input byte
and returns true if that BVL_DR.KALAM
byte is COMPUTING
nonzero, false
CENTRE, MIT if that byte is zero.
28-Aug-25 33
CAMPUS ANNA UNIVERSITY
Method & Description
byte readByte()  This method reads and returns one input
byte.
char readChar()  This method reads two input bytes and
returns a char value.
double readDouble()  This method reads eight input bytes
and returns a double value.
float readFloat()  This method reads four input bytes and
returns a float value.
void readFully(byte[] b) This method reads some bytes from
an input stream and stores them into the buffer array b.
void readFully(byte[] b, int off, int len) This method
reads len bytes from an input stream.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 34
CAMPUS ANNA UNIVERSITY
int readInt()  This method reads four input bytes and returns an int
value.
long readLong() This method reads eight input bytes and returns a
long value.
short readShort()  This method reads two input bytes and returns a
short value.
int readUnsignedByte() This method reads one input byte, zero-
extends it to type int, and returns the result, which is therefore in
the range 0 through 255.
int readUnsignedShort()  This method reads two input bytes and
returns an int value in the range 0 through 65535.
String readUTF()  This method reads in a string that has been
encoded using a modified UTF-8 format.
static String readUTF(DataInput in)  This method reads from the
stream in a representation of a Unicode character string encoded in
modified UTF-8 format; this string of characters is then returned as a
String.
int skipBytes(int n) This method makes an attempt to skip over n
bytes of data from the input stream, discarding the skipped bytes.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 35
CAMPUS ANNA UNIVERSITY
DataOutputStream
• It lets an application write primitive java data types
to an output stream in a portable way.
• An application can use a DataInputStream to read
the data back in.
• constructor
DataOutputStream(OutputStream out)
This creates a new data output stream to write
data to the specified underlying output stream.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 36
CAMPUS ANNA UNIVERSITY
Method & Description
void flush() This method flushes this data output stream.
int size() This method returns the current value of the
counter written, the number of bytes written to this data
output stream so far.
void write(byte[] b, int off, int len) This method writes len
bytes from the specified byte array starting at offset off to
the underlying output stream.
void write(int b)  This method writes the specified byte (the
low eight bits of the argument b) to the underlying output
stream.
void writeBoolean(boolean v) This method writes a
boolean to the underlying output stream as a 1-byte value.
void writeByte(int v)  This method writes out a byte to the
underlying output stream as a 1-byte value.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 37
CAMPUS ANNA UNIVERSITY
Method & Description
void writeBytes(String s) This method writes out the string to
the underlying output stream as a sequence of bytes.
void writeChar(int v) This method writes a char to the
underlying output stream as a 2-byte value, high byte first.
void writeChars(String s)This method writes a string to the
underlying output stream as a sequence of characters
void writeDouble(double v) This method converts the double
argument to a long using the doubleToLongBits method in
class Double, and then writes that long value to the
underlying output stream as an 8-byte quantity, high byte
first.
void writeFloat(float v) This method converts the float
argument to an int using the floatToIntBits method in class
Float, and then writes that int value to the underlying output
stream as a 4-byte quantity, high byte first.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 38
CAMPUS ANNA UNIVERSITY
Method & Description
void writeInt(int v)
This method writes an int to the underlying output stream
as four bytes, high byte first.
void writeLong(long v)
This method writes a long to the underlying output stream
as eight bytes, high byte first.
void writeShort(int v)
This method writes a short to the underlying output
stream as two bytes, high byte first.
void writeUTF(String str)
This method writes a string to the underlying output
stream using modified UTF-8 encoding in a machine-
independent manner.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 39
CAMPUS ANNA UNIVERSITY
import java.io.*;
class DataInputStreamEx1 DataInputStream/DataOutputStream Example 1
{
public static void main(String a[])
{
try
{
FileOutputStream fout=new FileOutputStream("in3.txt");
DataOutputStream dsout=new DataOutputStream(fout);
for(int i=0;i<10;i++)
dsout.writeInt(i);
fout.close();
FileInputStream fin=new FileInputStream("in3.txt");
DataInputStream dsin=new DataInputStream(fin);
int c;
while(dsin.available()>0)
{
c=dsin.readInt();
System.out.print(c+" ");
}
}catch(Exception e) {
System.out.println("Exception:"+e);
}
} 28-Aug-25 BVL_DR.KALAM COMPUTING CENTRE, MIT
40
CAMPUS ANNA UNIVERSITY
}
import java.io.*; DataInputStream Example2
class DataInputStreamEx2
{
public static void main(String a[])
{
try
{
FileInputStream fin=new FileInputStream("in.txt");
DataInputStream dsin=new DataInputStream(fin);
int c=dsin.available();
System.out.println("c="+c);
byte b[]=new byte[c];
dsin.read(b);
for(int i=0;i<b.length;i++)
{
System.out.print((char)b[i]);
}
}catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
} 28-Aug-25 BVL_DR.KALAM COMPUTING CENTRE, MIT
41
CAMPUS ANNA UNIVERSITY
BufferedInputStream & BufferedOutputStream
• The functionality of these high level classes is to increase
the performance with buffer
• These streams give an implicit system-defined buffer
(generally 2048 bytes) into which data is read and written
• The buffer decreases the number of transfers between
source file context area and destination file context area
and there by performance increases
• The buffer works as a reservoir to store data
• A buffer stands in between an input stream and output
stream
• The data is read and put in the buffer instead of sending
immediately
28-Aug-25
BVL_DR.KALAM COMPUTING CENTRE, MIT
42
CAMPUS ANNA UNIVERSITY
BufferedInputStream & BufferedOutputStream
• When the buffer is full, the buffer is transferred. This
decreases the number of execution control shifting
between input and output streams and there by
performance increases
• The size of the buffer allocated depends on the
underlying operating system
• The size of buffer can be requested explicitly using
overloaded constructor of BufferedInputStream as
follows,
BufferedInputStream bis=new BufferedInputStream(fistream,6000)
• In the above statement, a buffer of 6000 bytes is
allocated by the OS.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 43
CAMPUS ANNA UNIVERSITY
Constructor & Description
1. BufferedInputStream(InputStream in)
This creates a BufferedInputStream and saves its
argument, the input stream in, for later use.

2. BufferedInputStream(InputStream in, int size)


This creates a BufferedInputStream with the specified
buffer size, and saves its argument, the input stream
in, for later use.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 44
CAMPUS ANNA UNIVERSITY
Method Description
int available() It returns an estimate number of bytes that can be
read from the input stream without blocking by the
next invocation method for the input stream.
int read() It read the next byte of data from the input stream.

int read(byte[] b, int It read the bytes from the specified byte-input
off, int ln) stream into a specified byte array, starting with the
given offset.
void close() It closes the input stream and releases any of the
system resources associated with the stream.
void reset() It repositions the stream at a position the mark
method was last called on this input stream.
void mark(int It sees the general contract of the mark method for
readlimit) the input stream.
long skip(long x) It skips over and discards x bytes of data from the
input stream.
boolean It tests for the input stream to support the mark
markSupported()
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 45
CAMPUS ANNA UNIVERSITY
BufferedOutputStream
• It is used for buffering an output stream.
• It internally uses buffer to store data. It adds more efficiency
than to write data directly into a stream. So, it makes the
performance fast.
• By setting up such an output stream, an application can write
bytes to the underlying output stream without necessarily
causing a call to the underlying system for each byte written.
• constructors
BufferedOutputStream(OutputStream out)
This creates a new buffered output stream to write data to the
specified underlying output stream.
BufferedOutputStream(OutputStream out, int size)
This creates a new buffered output stream to write data to the
specified underlying output stream with the specified buffer
size.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 46
CAMPUS ANNA UNIVERSITY
Method Description

void write(int b) It writes the specified byte to the


buffered output stream.
void write(byte[] b, It write the bytes from the specified
int off, int len) byte-input stream into a specified byte
array, starting with the given offset

void flush() It flushes the buffered output stream

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 47
CAMPUS ANNA UNIVERSITY
BufferedInputStream & BufferedOutputStream Example

import java.io.*;
class BufferedEx
{
public static void main(String args[])throws Exception
{
try
{
FileOutputStream fout=new FileOutputStream("f1.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Good Morning, Have a great day";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("successfully written in file...");
System.out.println("\nReading from file...");
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 48
CAMPUS ANNA UNIVERSITY
int i;
while((i=bin.read())!=-1)
{
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 49
CAMPUS ANNA UNIVERSITY
PushbackInputStream
• Push back is used as an input stream to allow a byte
to be read and then returned(unread) (i.e: “pushed
back”) to the stream
• The PushbackInputStream class implements this idea
• It provides a mechanism to “peek” at what is coming
from an input stream without disturbing it.
• Constructor & Description
PushbackInputStream(InputStream in)
This creates a PushbackInputStream and saves its
argument, the input stream in, for later use.
PushbackInputStream(InputStream in, int size)
This creates a PushbackInputStream with a pushback
buffer of the specified size, and saves its argument,
the input stream in, for later use.
28-Aug-25
BVL_DR.KALAM COMPUTING CENTRE, MIT
50
CAMPUS ANNA UNIVERSITY
Method Description
int available() It is used to return the number of bytes
that can be read from the input stream.
int read() It is used to read the next byte of data
from the input stream.
boolean markSupported() It tests if this input stream supports the
mark and reset methods, which it does not.
void mark(int readlimit) It is used to mark the current position in
the input stream.

long skip(long x) It is used to skip over and discard x bytes


of data.
void unread(int b) It is used to pushes back the byte by
copying it to the pushback buffer.
void unread(byte[] b) It is used to pushes back the array of byte
by copying it to the pushback buffer.
void reset() It is used to reset the input stream.
void close() It is used to close the input stream.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 51
CAMPUS ANNA UNIVERSITY
import java.io.ByteArrayInputStream;
import java.io.IOException; PushbackInputStream Example
import java.io.PushbackInputStream;
public class PushbackInputStreamExample
{
public static void main(String[] args)
{
String strExpression = "a = a++ + b;";
byte bytes[] = strExpression.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
PushbackInputStream pis = new PushbackInputStream(bis);
int ch,c;
try
{
while( (ch = pis.read())!= -1)
{
if(ch == '+')
{
if( (ch = pis.read()) == '+')
{
System.out.print(“ Plus Plus");
}
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 52
CAMPUS ANNA UNIVERSITY
else
{
System.out.print("+");
}
}else
{
System.out.print((char)ch);
}
}
}
catch(IOException ioe)
{
System.out.println("Exception while reading" + ioe);
}
}
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 53
CAMPUS ANNA UNIVERSITY
PrintStream class
• This class prints java primitive values and object to a
stream as text
• The PrintStream class automatically flushes the
data so there is no need to call flush() method.
• None of the methods in this class throws an
Exception

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 54
CAMPUS ANNA UNIVERSITY
Constructor & Description
PrintStream(File file)
This creates a new print stream, without automatic line flushing, with the
specified file
PrintStream(File file, String csn)
This creates a new print stream, without automatic line flushing, with the
specified file and charset.
PrintStream(OutputStream out)
This creates a new print stream.
PrintStream(OutputStream out, boolean autoFlush)
This creates a new print stream.
PrintStream(OutputStream out, boolean autoFlush, String encoding)
This creates a new print stream.
PrintStream(String fileName)
This creates a new print stream, without automatic line flushing, with the
specified file name.
PrintStream(String fileName, String csn)
This creates a new print stream, without automatic line flushing, with the
specified file name andBVL_DR.KALAM
28-Aug-25 charset. COMPUTING CENTRE, MIT
CAMPUS ANNA UNIVERSITY
55
Method Description

void print(boolean b) It prints the specified boolean value.

void print(char c) It prints the specified char value.

void print(char[] c) It prints the specified character


array values.

void print(int i) It prints the specified int value.

void print(long l) It prints the specified long value.

void print(float f) It prints the specified float value.

void print(double d) It prints the specified double value.

void print(String s) It prints the specified string value.

void print(Object obj) It prints the specified object value.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 56
CAMPUS ANNA UNIVERSITY
void println(boolean b) It prints the specified boolean value
and terminates the line.
void println(char c) It prints the specified char value and
terminates the line.
void println(char[] c) It prints the specified character
array values and terminates the line.

void println(int i) It prints the specified int value and


terminates the line.
void println(long l) It prints the specified long value and
terminates the line.
void println(float f) It prints the specified float value and
terminates the line.
void println(double d) It prints the specified double value
and terminates the line.
void println(String s) It prints the specified string value
and terminates the line.
void println(Object obj) It prints the specified object value
and terminates the line.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 57
CAMPUS ANNA UNIVERSITY
PrintStreamExample
import java.io.*;
class PrintStreamTest
{
public static void main(String args[])throws Exception
{
FileOutputStream fout=new FileOutputStream("mfile.txt");
PrintStream pout=new PrintStream(fout);
pout.println(2500);
pout.println(12.5);
pout.println("Have a Gread day...");
pout.close();
fout.close();
pout=new PrintStream(System.out);
pout.print("welcome");
int c=10;
pout.print(c);
pout.close();
}
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 58
CAMPUS ANNA UNIVERSITY
PipedInputStream and PipedOutputStream
• PipedInputStream and PipedOutputStream are a pair of
Java I/O classes used for inter-thread communication.
• They act like a real-world pipe, where data written into one
end (PipedOutputStream) is read from the other end
(PipedInputStream).
• A PipedOutputStream must be connected to
a PipedInputStream to function.
• This can be done in one of two ways:
– Using connect() method:
• pipedOutputStream.connect(pipedInputStream);
– Passing the input stream into the output stream's constructor:
• PipedOutputStream pos = new PipedOutputStream(pipedInputStream);

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 59
CAMPUS ANNA UNIVERSITY
PipedInputStream and PipedOutputStream

Sr.No. Method & Description


int available()This method returns the number of bytes that can be read from this
1
input stream without blocking.

void close()This method closes this piped input stream and releases any system
2
resources associated with the stream.

void connect(PipedOutputStream src)This method causes this piped input


3
stream to be connected to the piped output stream src.

4 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
5
this piped input stream into an array of bytes.

6
28-Aug-25 protected void receive(int
BVL_DR.KALAM b)This method
COMPUTING receives
CENTRE, MIT a byte of data. 60
CAMPUS ANNA UNIVERSITY
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 61
CAMPUS ANNA UNIVERSITY
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 62
CAMPUS ANNA UNIVERSITY
ObjectInputStream and ObjectOutputStream
• These two classes in Java that are used to serialize
and deserialize Java objects, respectively.
• Serialization is the process of converting a Java
object into a stream of bytes that can be stored or
transmitted.
• Deserialization is the process of converting a stream
of bytes back into a Java object.
• ObjectInputStream and ObjectOutputStream are
used in a variety of applications, such as:
– Persisting Java objects to a file or database
– Sending Java objects over a network
– Saving and restoring the state of a Java object

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 63
CAMPUS ANNA UNIVERSITY
ObjectInputStream and ObjectOutputStream
• ObjectInputStream and ObjectOutputStream are both
AutoCloseable classes. (This means that they can be
automatically closed using the try-with-resources
statement).
• If we are writing to a file that does not exist,
ObjectOutputStream will create the file for you.
• If we are writing to a file that already exists,
ObjectOutputStream will overwrite the contents of the file.
• To append data to an existing file, we can use the
ObjectOutputStream constructor that takes a boolean
parameter.
• If we set this parameter to true, ObjectOutputStream will
append data to the end of the file instead of overwriting it.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 64
CAMPUS ANNA UNIVERSITY
Methods of ObjectInputStream Class

Method Description
Returns an estimate of the number of bytes that can be read (or
available() skipped over) from this input stream without blocking, which may be
0, or 0 when end of stream is detected.
Closes this input stream and releases any system resources associated
close()
with this stream.
Marks the current position in this input stream. A subsequent reset()
mark(int readlimit)
will attempt to reposition the stream to this point.
Tells whether this input stream supports the mark() and reset()
markSupported()
methods.
read() Reads a byte of data from this input stream.
Reads up to b.length bytes of data from this input stream into an array
read(byte[] b)
of bytes.
read(byte[] b, int off, Reads up to len bytes of data from this input stream into an array of
int len) bytes, starting at offset off in the array.
readObject() Reads an object from the input stream.
Repositions this stream to the position at which the last mark() was
reset()
set.
skip(long n) Skips overBVL_DR.KALAM
and discards n bytes
COMPUTING of data
CENTRE, MIT from this input stream.
28-Aug-25 65
CAMPUS ANNA UNIVERSITY
Methods of ObjectOutputStream Class

Method Description
Closes this output stream and releases
close() any system resources associated with
this stream.
Flushes this output stream and forces
flush() any buffered output bytes to be written
out to the underlying device.
writeObject(Object obj) Writes an object to the output stream.
Writes an object to the output stream
writeUnshared(Object obj)
without sharing.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 66
CAMPUS ANNA UNIVERSITY
ObjectInputStream and ObjectOutputStream – Example1 (Single Object Read Write)

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 67
CAMPUS ANNA UNIVERSITY
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 68
CAMPUS ANNA UNIVERSITY
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 69
CAMPUS ANNA UNIVERSITY
ObjectInputStream and ObjectOutputStream – Example1 (Multiple Objects Read Write)

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 70
CAMPUS ANNA UNIVERSITY
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 71
CAMPUS ANNA UNIVERSITY
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 72
CAMPUS ANNA UNIVERSITY
Reader & Writer classes
• The Java Reader and Java Writer class in Java IO work
much like the InputStream and OutputStream with
the exception that Reader and Writer are character
based.
• Input streams read bytes whereas readers are able to
read characters
• These are intended for reading and writing text.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 73
CAMPUS ANNA UNIVERSITY
BufferedReader LineNumberReader
CharArrayReader
FilterReader PushbackReader
Reader
InputStreamReader FileReader
PipedReader
StringReader
BufferedWriter
CharArrayWriter
FilterWriter
Writer
OutputStreamWriter FileWriter
PipedWriter
StringWriter
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 74
CAMPUS ANNA UNIVERSITY
PrintWriter
FileWriter & FileReader
• These classes are used to write and read data from
text files
• These are character oriented classes used for file
handling in java
• Java have suggested not to use the FileInputStream
and FileOutputStream classes if we have to read and
write the textual information

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 75
CAMPUS ANNA UNIVERSITY
FileWriter Class
• Java FileWriter class is used to write character-oriented
data to a file. It is character-oriented class which is used
for file handling in java.
• Unlike FileOutputStream class, you don't need to convert
string into byte array because it provides method to
write string directly.
• Constructors
1. FileWriter(String file)
Creates a new file. It gets file name in string.
2. FileWriter(File file)
Creates a new file. It gets file name in File object.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 76
CAMPUS ANNA UNIVERSITY
Method Description
void write(String text) It is used to write the string
into FileWriter.
void write(char c) It is used to write the char
into FileWriter.

void write(char[] c) It is used to write char array


into FileWriter.

void flush() It is used to flushes the data


of FileWriter.

void close() It is used to close the


FileWriter.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 77
CAMPUS ANNA UNIVERSITY
FileReader Class
• Java FileReader class is used to read data from the file.
It returns data in byte format like FileInputStream class.
• It is character-oriented class which is used for file
handling in java.
• Constructors
1.FileReader(String file)
It gets filename in string. It opens the given file in read
mode. If file doesn't exist, it throws
FileNotFoundException
2. FileReader(File file) It gets filename in file instance. It
opens the given file in read mode. If file doesn't exist, it
throws FileNotFoundException.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 78
CAMPUS ANNA UNIVERSITY
Method Description

int read() It is used to return a character in


ASCII form. It returns -1 at the end
of file.

void close() It is used to close the FileReader


class.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 79
CAMPUS ANNA UNIVERSITY
FileWriter & FileReader Example
import java.io.*;
class FileReaderWriterEx
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("file.txt");
fw.write("Welcome to java class");
fw.close();
System.out.println("successfully written in file");
FileReader fr=new FileReader("file.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 80
CAMPUS ANNA UNIVERSITY
CharArrayReader
• CharArrayReader implements a character buffer that
can be used as character-input stream
• It is similar to ByteArrayInputStream
• constructors
1. CharArrayReader(char[] buf)
This creates a CharArrayReader from the specified
array of chars.
2. CharArrayReader(char[] buf, int offset, int length)
This creates a CharArrayReader from the specified
array of chars.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 81
CAMPUS ANNA UNIVERSITY
Method Description

int read() It is used to read a single character


int read(char[] b, int It is used to read characters into the
off, int len) portion of an array.
boolean ready() It is used to tell whether the stream is
ready to read.
boolean It is used to tell whether the stream
markSupported() supports mark() operation.
long skip(long n) It is used to skip the character in the input
stream.
void mark(int It is used to mark the present position in
readAheadLimit) the stream.
void reset() It is used to reset the stream to a most
recent mark.
void close() It is used to closes the stream.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 82
CAMPUS ANNA UNIVERSITY
CharArrayWriter
• The CharArrayWriter class can be used to write
common data to multiple files.
• This class inherits Writer class.
• Its buffer automatically grows when data is written in
this stream.
• Calling the close() method on this object has no effect.
• constructors
1.CharArrayWriter()
This creates a CharArrayReader from the specified
array of chars.
2.CharArrayWriter(int initialSize)
This creates a new CharArrayWriter with the specified
initial size.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 83
CAMPUS ANNA UNIVERSITY
Method Description
int size() It is used to return the current size of the buffer.

char[] toCharArray() It is used to return the copy of an input data.

String toString() It is used for converting an input data to a string.

CharArrayWriter append(char It is used to append the specified character to the


c) writer.
CharArrayWriter It is used to append the specified character sequence
append(CharSequence csq) to the writer.
CharArrayWriter It is used to append the subsequence of a specified
append(CharSequence csq, int character to the writer.
start, int end)
void write(int c) It is used to write a character to the buffer.

void write(char[] c, int off, int It is used to write a character to the buffer.
len)
void write(String str, int off, int It is used to write a portion of string to the buffer.
len)
void writeTo(Writer out) It is used to write the content of buffer to different
character stream.
void flush() It is used to flush the stream.

void reset() It is used to reset the buffer.


BVL_DR.KALAM COMPUTING CENTRE, MIT
void28-Aug-25
close() It is used to close the stream.
CAMPUS ANNA UNIVERSITY
84
import java.io.*; CharArrayReader and Writer Example
public class CharArrayReaderWriterEx
{
public static void main(String args[])
{
try
{
char c[] = {'w','e','l','c','o','m','e','t','o','M','I','T'};
CharArrayReader r1 = new CharArrayReader(c);
CharArrayReader r2 = new CharArrayReader(c, 2, 5);
int i;
while((i = r1.read()) != -1)
{
System.out.print((char)i);
}
System.out.println();
while((i = r2.read()) != -1)
{
System.out.print((char)i);
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 85
CAMPUS ANNA UNIVERSITY
CharArrayWriter out = new CharArrayWriter();
out.write(c);
FileWriter f1 = new FileWriter("o1.txt");
out.writeTo(f1); //File written successfully.

FileWriter f2 = new FileWriter("o2.txt");


out.writeTo(f2); //File written successfully.

System.out.println("\nBuffer as a string");
System.out.println(out.toString());
System.out.println("\nInto array");
char ch[] = out.toCharArray();
for (i=0; i<ch.length; i++)
{
System.out.print(ch[i]);
}
f1.close();
f2.close();
//CharArrayWriter is closed.
out.close();

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 86
CAMPUS ANNA UNIVERSITY
FileWriter f3 = new FileWriter("o3.txt");
//Write again to a file. No Exception from CharArrayWriter but no data will be written.
out.writeTo(f3);
System.out.println("\nFile written successfully.");
}catch(Exception e)
{
System.out.println("Exception :"+e);
}
}
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 87
CAMPUS ANNA UNIVERSITY
StringReader
• It is a character stream with string as a source.
• It takes an input string and changes it into character
stream.
• It inherits Reader class.
• In StringReader class, system resources like network
sockets and files are not used, therefore closing the
StringReader is not necessary.
• constructor
StringReader(String s)
This creates a new string reader.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 88
CAMPUS ANNA UNIVERSITY
Method Description
int read() It is used to read a single character.
int read(char[] cbuf, It is used to read a character into a portion
int off, int len) of an array.
boolean ready() It is used to tell whether the stream is
ready to be read.
boolean It is used to tell whether the stream
markSupported() support mark() operation.
long skip(long ns) It is used to skip the specified number of
character in a stream
void mark(int It is used to mark the mark the present
readAheadLimit) position in a stream.
void reset() It is used to reset the stream.

void close() It is used to close the stream.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 89
CAMPUS ANNA UNIVERSITY
StringWriter
• It is a character stream that collects output from string
buffer, which can be used to construct a string. The
StringWriter class inherits the Writer class.
• In StringWriter class, system resources like network
sockets and files are not used, therefore closing the
StringWriter is not necessary.
• constructors
1. StringWriter()
This creates a new string writer using the default initial
string-buffer size.
2.StringWriter(int initialSize)
This creates a new string writer using the specified
initial string-bufferBVL_DR.KALAM
28-Aug-25
size. COMPUTING CENTRE, MIT 90
CAMPUS ANNA UNIVERSITY
Method Description
void write(int c) It is used to write the single character.
void write(String str) It is used to write the string.
void write(String str, int It is used to write the portion of a string.
off, int len)
void write(char[] cbuf, It is used to write the portion of an array of
int off, int len) characters.
String toString() It is used to return the buffer current value as a
string.
StringBuffer getBuffer() It is used t return the string buffer.
StringWriter It is used to append the specified character to the
append(char c) writer.
StringWriter It is used to append the specified character
append(CharSequence sequence to the writer.
csq)
StringWriter It is used to append the subsequence of specified
append(CharSequence character sequence to the writer.
csq, int start, int end)
void flush() It is used to flush the stream.
BVL_DR.KALAM COMPUTING CENTRE, MIT
void close()
28-Aug-25
It is CAMPUS
usedANNA
to close the stream.
UNIVERSITY
91
import java.io.*;
public class StringReaderWriterEx StringReader & Writer Example
{
public static void main(String[] args)
{
String str = "Good Morning! \nWelcome to MIT.";
StringReader sr = new StringReader(str);
int i=0;
try
{
while((i=sr.read())!=-1)
{
System.out.print((char)i);
}
String s = "Hello";
// create a new writer
StringWriter sw = new StringWriter();
// write strings
sw.write(s);
sw.write(" World");
// print result by converting to string
System.out.println(sw.toString());
} catch (IOException e) { System.out.println(“Exception:”+e);}
} BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 92
CAMPUS ANNA UNIVERSITY
}
InputStreamReader
• It is a bridge from byte streams to character streams.
• It reads bytes and decodes them into characters using a
specified charset.
• constructors
1. InputStreamReader(InputStream in)
This creates an InputStreamReader that uses the default
charset.
2. InputStreamReader(InputStream in, Charset cs)
This creates an InputStreamReader that uses the given
charset.
3. InputStreamReader(InputStream in, CharsetDecoder dec)
This creates an InputStreamReader that uses the given
charset decoder.
4. InputStreamReader(InputStream in, String charsetName)
This creates an InputStreamReader that uses the named
BVL_DR.KALAM COMPUTING CENTRE, MIT
charset.
28-Aug-25
CAMPUS ANNA UNIVERSITY
93
Method & Description
1. void close()This method closes the stream and
releases any system resources associated with it.
2. String getEncoding()This method returns the name
of the character encoding being used by this stream.
3. int read() This method reads a single character.
4. int read(char[] cbuf, int offset, int length) This
method reads characters into a portion of an array.
5. boolean ready() This method tells whether this
stream is ready to be read.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 94
CAMPUS ANNA UNIVERSITY
InputStreamReader Example

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 95
CAMPUS ANNA UNIVERSITY
BufferedReader
• It is used to read the text from a character-based input
stream.
• It can be used to read data line by line by readLine()
method.
• It makes the performance fast.
• It inherits Reader class.
• constructors
1. BufferedReader(Reader rd)
It is used to create a buffered character input stream
that uses the default size for an input buffer.
2. BufferedReader(Reader rd, int size)
It is used to create a buffered character input stream
that uses the specified
28-Aug-25
size
BVL_DR.KALAM for CENTRE,
COMPUTING an input
MIT buffer. 96
CAMPUS ANNA UNIVERSITY
Method Description
int read() It is used for reading a single character.
int read(char[] cbuf, It is used for reading characters into a
int off, int len) portion of an array.
boolean It is used to test the input stream support
markSupported() for the mark and reset method.
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is
ready to be read.
long skip(long n) It is used for skipping the characters.
void reset() It repositions the stream at a position the
mark method was last called on this input
stream.
void mark(int It is used for marking the present position in
readAheadLimit) a stream.
void close() It closes the input stream and releases any
ofBVL_DR.KALAM
the system resources
COMPUTING CENTRE, MIT associated with the
28-Aug-25 97
stream. CAMPUS ANNA UNIVERSITY
BufferedWriter
• It is used to provide buffering for Writer instances.
• It makes the performance fast.
• It inherits Writer class.
• The buffering characters are used for providing the efficient
writing of single arrays, characters, and strings.
• constructors
1. BufferedWriter(Writer wrt)
It is used to create a buffered character output stream that
uses the default size for an output buffer.
2. BufferedWriter(Writer wrt, int size)
It is used to create a buffered character output stream that
BVL_DR.KALAM COMPUTING CENTRE, MIT
uses the specified size CAMPUS
28-Aug-25 for an output buffer.
ANNA UNIVERSITY
98
Method Description

void newLine() It is used to add a new line by writing a


line separator.
void write(int c) It is used to write a single character.

void write(char[] cbuf, It is used to write a portion of an array


int off, int len) of characters.
void write(String s, int It is used to write a portion of a string.
off, int len)

void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 99
CAMPUS ANNA UNIVERSITY
import java.io.*; BufferedReader Example
public class BufferedReaderEx
{
public static void main(String args[])
{
try
{
FileReader fr=new FileReader("in.txt");
BufferedReader br=new BufferedReader(fr);
/*int i;
while((i=br.read())!=-1)
{
System.out.print((char)i);
}*/
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fr.close();
}catch(Exception e){System.out.println("Exception:"+e);}
}
BVL_DR.KALAM COMPUTING CENTRE, MIT
} 28-Aug-25 CAMPUS ANNA UNIVERSITY
100
import java.io.*; BufferedWriter Example
public class BufferedWriterEx
{
public static void main(String[] args)
{
try
{
FileWriter writer = new FileWriter("out.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to mit.");
buffer.newLine();
buffer.write("Good Morning");
buffer.close();
System.out.println("Success");
}catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 101
CAMPUS ANNA UNIVERSITY
FilterStreams (character)
• These are concrete classes that includes some
filtering capabilities as data is read (or) written by
another stream
• Eg. FilterReader object takes input from another
reader object and does processing for extra
functionality and returns the processed data.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 102
CAMPUS ANNA UNIVERSITY
FilterReader
• It is an abstract class of character streams with filter
capabilities on reading side
• Its equivalent in byte streams is FilterInputStream
• It includes only one sub class, PushbackReader
• Using PushbackReader is similar to PushbackInputStream

FilterWriter
• It is an abstract class for writing character data
• Its equivalent in byte streams is FilterOutputStream
• It does not have any sub class
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 103
CAMPUS ANNA UNIVERSITY
Files
• Files are primary source and destination for data within most
programs.
• Java devotes a whole range of methods found in a class called File in
the java.io package to perform these operations
• File is the only object in the I/O package that references an actual disk
file.
• File name should follow the conventions of the platform on which it is
loaded.
• Java treats Files and Directories as objects of File class.
• A directory is also treated as a file object with an additional property –
a list of file names that can be displayed using the list() method.
• Path separator, path separator character, file separator, file separator
character, depend on the platform on which we are working
• Example, if a windows based platform is being used, the path separator
should be “/”. Here if “\”, is used, it has to be escaped by mentioning
within a string.
28-Aug-25
BVL_DR.KALAM COMPUTING CENTRE, MIT
104
CAMPUS ANNA UNIVERSITY
Constructor
Constructor Description

File(String pathname) It creates a new File instance by converting the given


pathname string into an abstract pathname.
File file = new File("D:/Academic/web/file.txt");

File(File parent, String child) It creates a new File instance from a parent abstract
pathname and a child pathname string.
File parent = new File("D:/Academic/");
File file2 = new File(parent, “web/file2.txt");
File(String parent, String It creates a new File instance from a parent
child) pathname string and a child pathname string.
File file3 = new File("D:/Academic/",
“web/file3.txt");
File(URI uri) It creates a new File instance by converting the given
file: URI into an abstract pathname.
URI uri;
uri = new URI("file:///D:/Academic/web/file4.txt");
28-Aug-25 File file4COMPUTING
BVL_DR.KALAM = new CENTRE,
File(uri);
MIT
105
CAMPUS ANNA UNIVERSITY
Methods of File Class
Modifier and Type Method Description

static File createTempFile(String prefix, It creates an empty file in the default


String suffix) temporary-file directory, using the
given prefix and suffix to generate its
name.

boolean createNewFile() It atomically creates a new, empty


file named by this abstract
pathname if and only if a file with
this name does not yet exist.

boolean canWrite() It tests whether the application can


modify the file denoted by this
abstract pathname.String[]

boolean canExecute() It tests whether the application can


execute the file denoted by this
abstract pathname.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 106
CAMPUS ANNA UNIVERSITY
Modifier and Method Description
Type

boolean canRead() It tests whether the application can read the file
denoted by this abstract pathname.

boolean isAbsolute() It tests whether this abstract pathname is absolute.

boolean isDirectory() It tests whether the file denoted by this abstract


pathname is a directory.

boolean isFile() It tests whether the file denoted by this abstract


pathname is a normal file.

String getName() It returns the name of the file or directory denoted


by this abstract pathname.

String getParent() It returns the pathname string of this abstract


pathname's parent, or null if this pathname does not
name a parent directory.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 107
CAMPUS ANNA UNIVERSITY
Modifier and Method Description
Type

Path toPath() It returns a java.nio.file.Path object


constructed from the this abstract path.
URI toURI() It constructs a file: URI that represents this
abstract pathname.
File[] listFiles() It returns an array of abstract pathnames
denoting the files in the directory denoted by
this abstract pathname
long getFreeSpace() It returns the number of unallocated bytes in
the partition named by this abstract path
name.
String[] list(FilenameFilter filter) It returns an array of strings naming the files
and directories in the directory denoted by
this abstract pathname that satisfy the
specified filter.
boolean mkdir() It creates the directory named by this abstract
pathname.
BVL_DR.KALAM COMPUTING CENTRE, MIT
28-Aug-25 108
CAMPUS ANNA UNIVERSITY
Operations on File
• Creating a File
• Writing in a file
• Reading a file
• Copying a file
• Check File permissions
• Retrieving file information
• Deleting a file

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 109
CAMPUS ANNA UNIVERSITY
Creating a File ,
Check File permissions &
Retrieving file information

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 110
CAMPUS ANNA UNIVERSITY
File Class Example
import java.io.*;
public class File1
{
public static void main(String a[]) throws Exception
{
File f=new File("in.txt");
System.out.println("Name:"+f.getName());
System.out.println("path:"+f.getPath());
System.out.println("Absolute path:"+f.getAbsolutePath());
System.out.println(f.exists()?"file exist":"file does not exist");
System.out.println("Parent:"+f.getParent());
System.out.println(f.isFile()?"File":"Not file");
System.out.println(f.isDirectory()?"Directory":"Not Directory");
File f2=new File("i.txt");
System.out.println(f2.exists()?"i.txt file exist":"file does not exist");
f2.createNewFile();
System.out.println(f2.exists()?"i.txt file exist":"file does not exist");
System.out.println("Last Modified:"+f.lastModified());
System.out.println("length:"+f.length());

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 111
CAMPUS ANNA UNIVERSITY
File f3=new File("inn.txt");
f.renameTo(f3);
System.out.println(f2.canRead()?"can read file":"cannot read file");
System.out.println(f2.canWrite()?"can write file":"cannot write into file");
File f4=new File("Dir");
f4.mkdir();
System.out.println(f4.isFile()?"File":"Not file");
System.out.println(f4.isDirectory()?"Directory":"Not Directory");
System.out.println("Parent:"+f4.getParent());
File f5=new File("G:\\JAVA");
String s[]=f5.list();
for(int i=0;i<s.length;i++)
System.out.print(s[i]);
}
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 112
CAMPUS ANNA UNIVERSITY
Writing in a file,
Reading a file
Copying a file

Discussed in FileStream, FileReader &


FileWriter in I/O Streams Topic earlier

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 113
CAMPUS ANNA UNIVERSITY
Deleting a file

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 114
CAMPUS ANNA UNIVERSITY
Deleting a file
• We can use the delete() method of
the File class to delete the specified file or
directory.
• It returns,
– true if the file is deleted.
– false if the file does not exist.
• Note: We can only delete empty directories.

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 115
CAMPUS ANNA UNIVERSITY
Deleting a file Example
import java.io.File;
class FileDeleteEx
{
public static void main(String[] args)
{
// creates a file object
File file = new File("f.txt");
// deletes the file
boolean value = file.delete();
if(value)
{
System.out.println("The File is deleted.");
}
else
{
System.out.println("The File is not deleted.");
}
}
}

BVL_DR.KALAM COMPUTING CENTRE, MIT


28-Aug-25 116
CAMPUS ANNA UNIVERSITY

You might also like