You are on page 1of 80

Java IO

• Java uses stream stream and character based I/O


operation.
• The java.io package contains all the classes required for
input and output operations.
• A stream is a sequence of data. In Java, a stream is
composed of bytes.
• In Java, 3 streams are created for us automatically.
• System.out: standard output stream
• System.in: standard input stream
• System.err: standard error stream
• OutputStream: Java application uses an output stream to write
data to a destination; it may be a file, peripheral device or socket.
• InputStream:Java application uses an input stream to read data
from a source; it may be a file, peripheral device or socket.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 1
OutputStream class
• OutputStream class is an abstract class. It is the superclass of all
classes representing an output stream of bytes.
Method Description
is used to write a byte to the current
public void write(int)throws IOException
output stream.
public void write(byte[])throws is used to write an array of byte to the
IOException current output stream.
public void flush()throws IOException flushes the current output stream.
is used to close the current output
public void close()throws IOException
stream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 2
InputStream class
• InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.
Method Description
1) public abstract int read()throws reads the next byte of data from the input
IOException stream. It returns -1 at the end of the file.
returns an estimate of the number of bytes
2) public int available()throws
that can be read from the current input
IOException
stream.
3) public void close()throws
is used to close the current input stream.
IOException

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 3
FileOutputStream Class
• FileOutputStream is an output stream used for writing data to a file.
• FileOutputStream class methods

Method Description
It is used to clean up the connection with the file
protected void finalize()
output stream.
It is used to write ary.length bytes from the byte
void write(byte[] ary)
array to the file output stream.

void write(byte[] ary, int off, int It is used to write len bytes from the byte array
len) starting at offset off to the file output stream.

It is used to write the specified byte to the file


void write(int b)
output stream.
It is used to return the file descriptor associated
FileDescriptor getFD()
with the stream.

void close() It is used to closes the file output stream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 4
FileOutputStream Class
• FileOutputStream example
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to CGEC.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 5
FileInputStream Class
• FileInputStream class obtains input bytes from a file.
• FileInputStream class methods
Method Description
It is used to return the estimated number of bytes that
int available()
can be read from the input stream.

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

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 6
FileInputStream Class
• FileInputStream example

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 7
BufferedOutputStream Class
• Java BufferedOutputStream class is used for buffering an output
stream.
• It internally uses buffer to store data.
• Syntax:
OutputStream os= new BufferedOutputStream(new FileOutput
Stream("D:\\IO Package\\testout.txt"));
• BufferedOutputStream class constructors

Constructor Description
It creates the new buffered output
BufferedOutputStream(Outp
stream which is used for writing the
utStream os)
data to the specified output stream.
It creates the new buffered output
BufferedOutputStream(Outp stream which is used for writing the
utStream os, int size) data to the specified output stream
with a specified buffer size.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 8
BufferedOutputStream Class
• BufferedOutputStream class methods

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

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 9
BufferedOutputStream Class
• Example of BufferedOutputStream class
package com.javatpoint;
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

BufferedOutputStream bout=new BufferedOutputStream(fout);

String s="Welcome to javaTpoint.";


byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 10
BufferedInputStream Class
• Java BufferedInputStream class internally uses buffer mechanism to
make the performance fast.
• When a BufferedInputStream is created, an internal buffer array is
created.
• Syntax:
BufferedInputStream is= new BufferedInputStream(new FileInput
Stream("D:\\IO Package\\testout.txt"));
• BufferedOutputStream class constructors
Constructor Description
It creates the BufferedInputStream and
BufferedInputStream(InputS
saves it argument, the input stream IS,
tream IS)
for later use.
It creates the BufferedInputStream with
BufferedInputStream(InputS a specified buffer size and saves it
tream IS, int size) argument, the input stream IS, for later
use.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 11
BufferedInputStream Class
• BufferedInputStream class methods
Method Description
It returns an estimate number of bytes that can
be read from the input stream without blocking
int available()
by the next invocation method for the input
stream.
It read the next byte of data from the input
int read()
stream.
It read the bytes from the specified byte-input
int read(byte[] b, int off,
stream into a specified byte array, starting with
int ln)
the given offset.
It closes the input stream and releases any of
void close() the system resources associated with the
stream.
It repositions the stream at a position the mark
void reset()
method was last called on this input stream.
It skips over and discards x bytes of data from
long skip(long x)
the input stream.
Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 12
BufferedInputStream Class
• Example of BufferedInputStream class
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");

BufferedInputStream bin=new BufferedInputStream(fin);


int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 13
SequenceInputStream Class
• SequenceInputStream class is used to read data from multiple
streams. It reads data sequentially (one by one).
• SequenceInputStream Class declaration
public class SequenceInputStream extends InputStream
• Constructors of SequenceInputStream class

Constructor Description
creates a new input stream by
SequenceInputStream(Input reading the data of two input
Stream s1, InputStream s2) stream in order, first s1 and then
s2.

creates a new input stream by


SequenceInputStream(Enum
reading the data of an enumeration
eration e)
whose type is InputStream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 14
SequenceInputStream Class
• Methods of SequenceInputStream class

Method Description
It is used to read the next byte of data
int read()
from the input stream.
int read(byte[] ary, int It is used to read len bytes of data from
off, int len) the input stream into the array of bytes.
It is used to return the maximum
int available() number of byte that can be read from
an input stream.
void close() It is used to close the input stream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 15
SequenceInputStream Class
• Example of SequenceInputStream class
import java.io.*;
class InputStreamExample {
public static void main(String args[])throws Exception{
FileInputStream input1=new FileInputStream("D:\\testin.txt");
FileInputStream input2=new FileInputStream("D:\\testout.txt");
SequenceInputStream inst=new SequenceInputStream(input1, inpu
t2);
int j;
while((j=inst.read())!=-1){
System.out.print((char)j);
}
inst.close();
input1.close();
input2.close();
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 16
SequenceInputStream Class
• Example that reads the data from two files and writes into another
file
import java.io.*;
class Input1{
public static void main(String args[])throws Exception{
FileInputStream fin1=new FileInputStream("D:\\testin1.txt");
FileInputStream fin2=new FileInputStream("D:\\testin2.txt");
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
SequenceInputStream sis=new SequenceInputStream(fin1,fin2);
int i;
while((i=sis.read())!=-1)
{
fout.write(i);
}
sis.close();
fout.close();
fin1.close();
fin2.close();
System.out.println("Success..");
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 17

SequenceInputStream Class
• SequenceInputStream example that reads data using enumeration
import java.io.*;
import java.util.*;
class Input2{
public static void main(String args[])throws IOException{
//creating the FileInputStream objects for all the files
FileInputStream fin=new FileInputStream("D:\\a.txt");
FileInputStream fin2=new FileInputStream("D:\\b.txt");
FileInputStream fin3=new FileInputStream("D:\\c.txt");
FileInputStream fin4=new FileInputStream("D:\\d.txt");
//creating Vector object to all the stream
Vector v=new Vector();
v.add(fin);
v.add(fin2);
v.add(fin3);
v.add(fin4);
//creating enumeration object by calling the elements method
Enumeration e=v.elements();
//passing the enumeration object in the constructor
SequenceInputStream bin=new SequenceInputStream(e);
int i=0;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
fin2.close();
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 18
ByteArrayOutputStream Class
• Java ByteArrayOutputStream class is used to write common data
into multiple files.
• The ByteArrayOutputStream holds a copy of data and forwards it to
multiple streams.
• The buffer of ByteArrayOutputStream automatically grows according
to data.
• Java ByteArrayOutputStream class constructors

Constructor Description
Creates a new byte array output stream
ByteArrayOutputStream() with the initial capacity of 32 bytes,
though its size increases if necessary.
Creates a new byte array output stream,
ByteArrayOutputStream(int
with a buffer capacity of the specified
size)
size, in bytes.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 19
ByteArrayOutputStream Class
• Java ByteArrayOutputStream class methods
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.

It is used for converting the content into a string decoding bytes


String toString()
using a platform default character set.

String toString(String It is used for converting the content into a string decoding bytes
charsetName) using a specified charsetName.
It is used for writing the byte specified to the byte array output
void write(int b)
stream.

void write(byte[] b, int off, It is used for writing len bytes from specified byte array starting
int len from the offset off to the byte array output stream.

void writeTo(OutputStream It is used for writing the complete content of a byte array output
out) stream to the specified output stream.
It is used to reset the count field of a byte array output stream to
void reset()
zero value.
void close() It is used to close the ByteArrayOutputStream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 20
ByteArrayOutputStream Class
• Example of Java ByteArrayOutputStream
package com.javatpoint;
import java.io.*;
public class DataStreamExample {
public static void main(String args[])throws Exception{
FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");
FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");

ByteArrayOutputStream bout=new ByteArrayOutputStream();


bout.write(65);
bout.writeTo(fout1);
bout.writeTo(fout2);

bout.flush();
bout.close();//has no effect
System.out.println("Success...");
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 21
ByteArrayInputStream Class
• Java ByteArrayInputStream class is used to read byte array as input
stream.
• Java ByteArrayInputStream class contains an internal buffer which is
used to read byte array as stream.
• Java ByteArrayInputStream class constructors

Constructor Description
Creates a new byte array input
ByteArrayInputStream(byte[]
stream which uses ary as its buffer
ary)
array.
Creates a new byte array input
ByteArrayInputStream(byte[] stream which uses ary as its buffer
ary, int offset, int len) array that can read up to specified
len bytes of data from an array.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 22
ByteArrayOutputStream Class
• Java ByteArrayInputStream class methods

Methods Description
It is used to return the number of remaining
int available() bytes that can be read from the input
stream.
It is used to read the next byte of data from
int read()
the input stream.
int read(byte[] ary, int off, It is used to read up to len bytes of data
int len) from an array of bytes in the input stream.
It is used to skip the x bytes of input from
long skip(long x)
the input stream.
void reset() It is used to reset the buffer of a byte array.
It is used for closing a
void close()
ByteArrayInputStream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 23

ByteArrayOutputStream Class
• Example of Java ByteArrayInputStream
import java.io.*;
public class ReadExample {
public static void main(String[] args) throws IOException {
byte[] buf = { 35, 36, 37, 38 };
// Create the new byte array input stream
ByteArrayInputStream byt = new ByteArrayInputStream(buf)
;
int k = 0;
while ((k = byt.read()) != -1) {
//Conversion of a byte into character
char ch = (char) k;
System.out.println("ASCII value of Character is:" + k + "; S
pecial character is: " + ch);
}
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 24

DataOutputStream Class
• Java DataOutputStream class allows an application to write primitive
Java data types to the output stream in a machine-independent way.
• Java DataOutputStream class methods
Method Description
It is used to return the number of bytes written to the
int size()
data output stream.
It is used to write the specified byte to the
void write(int b)
underlying output stream.
void write(byte[] b, int off, int It is used to write len bytes of data to the output
len) stream.
It is used to write Boolean to the output stream as a
void writeBoolean(boolean v)
1-byte value.
It is used to write char to the output stream as a
void writeChar(int v)
2-byte value.
It is used to write string to the output stream as a
void writeChars(String s)
sequence of characters.
It is used to write a byte to the output stream as a
void writeByte(int v)
1-byte value.
It is used to write string to the output stream as a
void writeBytes(String s)
sequence of bytes.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 25

DataOutputStream Class
• Java DataOutputStream class methods…
Method Description
It is used to write an int to the output
void writeInt(int v)
stream
It is used to write a short to the output
void writeShort(int v)
stream.
It is used to write a short to the output
void writeShort(int v)
stream.
It is used to write a long to the output
void writeLong(long v)
stream.
It is used to write a string to the output
void writeUTF(String
stream using UTF-8 encoding in
str)
portable manner.
It is used to flushes the data output
void flush()
stream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 26
DataOutputStream Class
• Example of DataOutputStream class
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 27

DataInputStream Class
• Java DataInputStream class allows an application to read primitive
data from the input stream in a machine-independent way.
• Java DataInputStream class Methods
Method Description
It is used to read the number of bytes
int read(byte[] b)
from the input stream.
int read(byte[] b, int off, int It is used to read len bytes of data from
len) the input stream.
It is used to read input bytes and return
int readInt()
an int value.
It is used to read and return the one input
byte readByte()
byte.
It is used to read two input bytes and
char readChar()
returns a char value.
It is used to read eight input bytes and
double readDouble()
returns a double value.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 28

DataInputStream Class
• Java DataInputStream class Methods

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

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 29

DataInputStream Class
• Example of DataInputStream class
package com.javatpoint;
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 30

FilterOutputStream Class
• Java FilterOutputStream class implements the OutputStream class. It
provides different sub classes such as BufferedOutputStream and
DataOutputStream to provide additional functionality.
• Java FilterOutputStream class Methods

Method Description
It is used to write the specified byte to the
void write(int b)
output stream.
It is used to write ary.length byte to the
void write(byte[] ary)
output stream.
void write(byte[] b, It is used to write len bytes from the offset
int off, int len) off to the output stream.
void flush() It is used to flushes the output stream.
void close() It is used to close the output stream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 31
FilterOutputStream Class
• Example of FilterOutputStream class
public class FilterExample {
public static void main(String[] args) throws IOException {
File data = new File("D:\\testout.txt");
FileOutputStream file = new FileOutputStream(data);
FilterOutputStream filter = new FilterOutputStream(file);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
filter.write(b);
filter.flush();
filter.close();
file.close();
System.out.println("Success...");
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 32

Console Class
• Java Console class is be used to get input from console. It provides
methods to read texts and passwords.
• Java Console class methods
Method Description
It is used to retrieve the reader object associated
Reader reader()
with the console
It is used to read a single line of text from the
String readLine()
console.
String readLine(String fmt, Object... It provides a formatted prompt then reads the
args) single line of text from the console.
It is used to read password that is not being
char[] readPassword()
displayed on the console.
It provides a formatted prompt then reads the
char[] readPassword(String fmt,
password that is not being displayed on the
Object... args)
console.
Console format(String fmt, Object... It is used to write a formatted string to the console
args) output stream.
Console printf(String format, It is used to write a string to the console output
Object... args) stream.
It is used to retrieve the PrintWriter object
PrintWriter writer()
associated with the console.
void flush() It is used
Sukhendu Shekhar Mondal, Assistant Professor, to flushes
Cooch the console.
Behar Government Engineering College 33

Writer Class
• It is an abstract class for writing to character streams.
• The methods that a subclass must implement are
write(char[], int, int), flush(), and close().
• Constructor
Modifier Constructor Description
It creates a new character-stream writer
protected Writer() whose critical sections will synchronize
on the writer itself.
It creates a new character-stream writer
protected Writer(Object lock) whose critical sections will synchronize
on the given object.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 34

Writer Class
• Methods
Modifier and
Method Description
Type
It appends the specified character to
Writer append(char c)
this writer.
It appends the specified character
Writer append(CharSequence csq)
sequence to this writer
It appends a subsequence of the
append(CharSequence csq,
Writer specified character sequence to this
int start, int end)
writer.
abstract void close() It closes the stream, flushing it first.
abstract void flush() It flushes the stream.
void write(char[] cbuf) It writes an array of characters.
write(char[] cbuf, int off, int It writes a portion of an array of
abstract void
len) characters.
void write(int c) It writes a single character.
void write(String str) It writes a string.
write(String str, int off, int
void It writes a portion of a string.
len)

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 35
Writer Class
• Java Writer Example
public class WriterExample {
public static void main(String[] args) {
try {
Writer w = new FileWriter("output.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 36

Reader Class
• Java Reader is an abstract class for reading character
streams.
• The only methods that a subclass must implement are
read(char[], int, int) and close().
• Constructor
Modifier Constructor Description
It creates a new character-stream
protected Reader() reader whose critical sections will
synchronize on the reader itself.
It creates a new character-stream
Reader(Object
protected reader whose critical sections will
lock)
synchronize on the given object.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 37

Reader Class
• Methods
Modifier
Method Description
and Type

abstract It closes the stream and releases any system


close()
void resources associated with it.

void mark(int readAheadLimit) It marks the present position in the stream.

It tells whether this stream supports the mark()


boolean markSupported()
operation.
int read() It reads a single character.

int read(char[] cbuf) It reads characters into an array.


read(char[] cbuf, int off, int
abstract int It reads characters into a portion of an array.
len)
It attempts to read characters into the specified
int read(CharBuffer target)
character buffer.

boolean ready() It tells whether this stream is ready to be read.

void reset() It resets the stream.


long skip(long n) It skips characters.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 38

Reader Class
• Example
import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 39

FileWriter Class
• Java FileWriter class is used to write character-oriented
data to a file.
• Unlike FileOutputStream class, you don't need to convert
string into byte array because it provides method to write
string directly.
• Constructors of FileWriter class

Constructor Description
FileWriter(String Creates a new file. It gets file name in
file) string.
Creates a new file. It gets file name in
FileWriter(File file)
File object.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 40

FileWriter Class
• Methods of FileWriter class
Method Description
void write(String
It is used to write the string into FileWriter.
text)
void write(char c) It is used to write the char into FileWriter.
void write(char[]
It is used to write char array into FileWriter.
c)
void flush() It is used to flushes the data of FileWriter.
void close() It is used to close the FileWriter.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 41

FileWriter Class
• Java FileWriter Example
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 42

FileReader Class
• Java FileReader class is used to read data from the file.
• It is character-oriented class which is used for file
handling in java.
• Constructors of FileReader class
Constructor Description
It gets filename in string. It opens the
FileReader(String
given file in read mode. If file doesn't
file)
exist, it throws FileNotFoundException.
It gets filename in file instance. It opens
FileReader(File
the given file in read mode. If file doesn't
file)
exist, it throws FileNotFoundException.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 43
FileReader Class
• Methods of FileReader class
Method Description
It is used to return a character in ASCII form. It
int read()
returns -1 at the end of file.
void close() It is used to close the FileReader class.
• FileReader Example
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 44
BufferedWriter Class
• Java BufferedWriter class is used to provide buffering for
Writer instances.
• It inherits Writer class.
• The buffering characters are used for providing the
efficient writing of single arrays, characters, and strings.
• constructors
Constructor Description
It is used to create a buffered
BufferedWriter(Writer wrt) character output stream that uses
the default size for an output buffer.
It is used to create a buffered
BufferedWriter(Writer wrt, int character output stream that uses
size) the specified size for an output
buffer.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 45
BufferedWriter Class
• Methods
Method Description
It is used to add a new line by
void newLine()
writing a line separator.
void write(int c) It is used to write a single character.
void write(char[] cbuf, int It is used to write a portion of an
off, int len) array of characters.
void write(String s, int off, It is used to write a portion of a
int len) string.
It is used to flushes the input
void flush()
stream.
void close() It is used to closes the input stream

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 46
BufferedWriter Class
• Example of Java BufferedWriter
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to javaTpoint.");
buffer.close();
System.out.println("Success");
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 47
BufferedReader Class
• Java BufferedReader class 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 inherits Reader class.
• BufferedReader class constructors
Constructor Description
It is used to create a buffered character
BufferedReader(Reader
input stream that uses the default size for
rd)
an input buffer.
It is used to create a buffered character
BufferedReader(Reader rd,
input stream that uses the specified size for
int size)
an input buffer.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 48
BufferedReader Class
• BufferedReader class methods
Method Description
int read() It is used for reading a single character.
int read(char[] cbuf, int off, It is used for reading characters into a portion of an
int len) array.
It is used to test the input stream support for the
boolean markSupported()
mark and reset method.
String readLine() It is used for reading a line of text.
It is used to test whether the input stream is ready to
boolean ready()
be read.
long skip(long n) It is used for skipping the characters.
It repositions the stream at a position the mark
void reset()
method was last called on this input stream.
void mark(int It is used for marking the present position in a
readAheadLimit) stream.
It closes the input stream and releases any of the
void close()
system resources associated with the stream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 49

BufferedReader Class
• BufferedReader Example
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);

int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 50

BufferedReader Class
• Reading data from console by InputStreamReader and
BufferedReader
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(r);


System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 51

CharArrayReader Class
• The CharArrayReader is composed of two words: CharArray and
Reader.
• The CharArrayReader class is used to read character array as a
reader (stream). It inherits Reader class.
• CharArrayReader class methods
Method Description
int read() It is used to read a single character
int read(char[] b, int off, int It is used to read characters into the portion of an
len) array.
It is used to tell whether the stream is ready to
boolean ready()
read.
It is used to tell whether the stream supports
boolean markSupported()
mark() operation.
long skip(long n) It is used to skip the character in the input stream.
It is used to mark the present position in the
void mark(int readAheadLimit)
stream.
It is used to reset the stream to a most recent
void reset()
mark.
Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 52
void close() It is used to closes the stream.

CharArrayReader Class
• Example of CharArrayReader Class:
import java.io.CharArrayReader;
public class CharArrayExample{
public static void main(String[] ag) throws Exception {
char[] ary = { 'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't' };
CharArrayReader reader = new CharArrayReader(ary);
int k = 0;
// Read until the end of a file
while ((k = reader.read()) != -1) {
char ch = (char) k;
System.out.print(ch + " : ");
System.out.println(k);
}
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 53

CharArrayWriter Class
• CharArrayWriter Class
• 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.
• CharArrayWriter class Methods
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.
It is used to append the specified character to the
CharArrayWriter append(char c)
writer.
CharArrayWriter It is used to append the specified character sequence
append(CharSequence csq) to the writer.
void write(int c) It is used to write a character to the buffer.
void write(char[] c, int off, int len) It is used to write a character to the buffer.
void write(String str, int off, int
It is used to write a portion of string to the buffer.
len)
It is used to write the content of buffer to different
void writeTo(Writer out)
character stream.
Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 54
void reset() It is used to reset the buffer.
CharArrayWriter Class
• Example of CharArrayWriter Class:
import java.io.CharArrayWriter;
import java.io.FileWriter;
public class CharArrayWriterExample {
public static void main(String args[])throws Exception{
CharArrayWriter out=new CharArrayWriter();
out.write("Welcome to javaTpoint");
FileWriter f1=new FileWriter("D:\\a.txt");
FileWriter f2=new FileWriter("D:\\b.txt");
FileWriter f3=new FileWriter("D:\\c.txt");
FileWriter f4=new FileWriter("D:\\d.txt");
out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
System.out.println("Success...");
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 55
PrintStream Class
• The PrintStream class provides methods to write data to another
stream.
• The PrintStream class automatically flushes the data.
• Its methods don't throw IOException.
• Methods of PrintStream class
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.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 56
PrintStream Class
• Methods of PrintStream class
Method Description
void print(Object
It prints the specified object value.
obj)
void println(boolean It prints the specified boolean value and
b) terminates the line.
It prints the specified char value and terminates
void println(char c)
the line.
It prints the specified character array values
void println(char[] c)
and terminates the line.
It prints the specified int value and terminates
void println(int i)
the line.
It prints the specified long value and terminates
void println(long l)
the line.
It prints the specified float value and terminates
void println(float f)
the line.
void println(double It prints the specified double value and
d) Sukhendu Shekhar Mondal,terminates
Assistant Professor, Cooch Behar Government Engineering College
the line. 57
PrintStream Class
• Methods of PrintStream class
Method Description
It prints the specified string value and
void println(String s)
terminates the line.
void println(Object It prints the specified object value and
obj) terminates the line.
void println() It terminates the line only.
void printf(Object
It writes the formatted string to the current
format, Object...
stream.
args)
void printf(Locale l,
It writes the formatted string to the current
Object format,
stream.
Object... args)
void format(Object
It writes the formatted string to the current
format, Object...
stream using specified format.
args)
void format(Locale l,
It writes the formatted string to the current
ObjectSukhendu
format,Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 58
stream using specified format.
PrintStream Class
• Example of java PrintStream class
import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");
PrintStream pout=new PrintStream(fout);
pout.println(2016);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
System.out.println("Success?");
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 59
PrintStream Class
• Example of printf() method using java PrintStream class:
class PrintStreamTest{
public static void main(String args[]){
int a=19;
System.out.printf("%d",a); //Note: out is the object of printstream
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 60
PrintWriter class
• PrintWriter class is the implementation of Writer class.
• It is used to print the formatted representation of objects to the
text-output stream.
• Methods of PrintWriter class
Method Description
void println(boolean x) It is used to print the boolean value.
void println(char[] x) It is used to print an array of characters.
void println(int x) It is used to print an integer.
It is used to append the specified character
PrintWriter append(char c)
to the writer.
PrintWriter
It is used to append the specified character
append(CharSequence
sequence to the writer.
ch)
PrintWriter
It is used to append a subsequence of
append(CharSequence
specified character to the writer.
ch, int start, int end)
It is used to flushes the stream and check
boolean checkError()
its error state.
Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 61
PrintWriter class
• Methods of PrintWriter class
Method Description
protected void setError() It is used to indicate that an error occurs.
It is used to clear the error state of a
protected void clearError()
stream.
It is used to write a formatted string to the
PrintWriter format(String
writer using specified arguments and format
format, Object... args)
string.
void print(Object obj) It is used to print an object.
void flush() It is used to flushes the stream.
void close() It is used to close the stream.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 62
PrintWriter class
• Java PrintWriter Example
import java.io.File;
import java.io.PrintWriter;
public class PrintWriterExample {
public static void main(String[] args) throws Exception {
//Data to write on Console using PrintWriter
PrintWriter writer = new PrintWriter(System.out);
writer.write("Javatpoint provides tutorials of all technology.");
writer.flush();
writer.close();
//Data to write in File using PrintWriter
PrintWriter writer1 =null;
writer1 = new PrintWriter(new File("D:\\testout.txt"));
writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");

writer1.flush();
writer1.close();
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 63
OutputStreamWriter
• OutputStreamWriter is a class which is used to convert character
stream to byte stream, the characters are encoded into byte using a
specified charset.
• write() method calls the encoding converter which converts the
character into bytes.
• Constructor
Constructor Description
It creates an OutputStreamWriter
OutputStreamWriter(OutputStream
that uses the default character
out)
encoding.
OutputStreamWriter(OutputStream It creates an OutputStreamWriter
out, Charset cs) that uses the given charset.
OutputStreamWriter(OutputStream It creates an OutputStreamWriter
out, CharsetEncoder enc) that uses the given charset encoder.
OutputStreamWriter(OutputStream It creates an OutputStreamWriter
out, String charsetName) that uses the named charset.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 64
OutputStreamWriter
• Methods

Modifier and
Method Description
Type
It closes the stream, flushing it
void close()
first.
void flush() It flushes the stream.
It returns the name of the
String getEncoding() character encoding being used
by this stream.
write(char[] cbuf, int It writes a portion of an array of
void
off, int len) characters.
void write(int c) It writes a single character.
write(String str, int off,
void It writes a portion of a string.
int len)

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 65
OutputStreamWriter
• Example
public class OutputStreamWriterExample {
public static void main(String[] args) {

try {
OutputStream outputStream = new FileOutputStream("output.txt");
Writer outputStreamWriter = new OutputStreamWriter(outputStream);

outputStreamWriter.write("Hello World");

outputStreamWriter.close();
} catch (Exception e) {
e.getMessage();
}
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 66
InputStreamReader
• An InputStreamReader is a bridge from byte streams to character
streams: It reads bytes and decodes them into characters using a
specified charset.
• Constructors
Constructor name Description
InputStreamReader(InputStrea It creates an InputStreamReader that
m in) uses the default charset.
InputStreamReader(InputStrea It creates an InputStreamReader that
m in, Charset cs) uses the given charset.
InputStreamReader(InputStrea It creates an InputStreamReader that
m in, CharsetDecoder dec) uses the given charset decoder.
InputStreamReader(InputStrea It creates an InputStreamReader that
m in, String charsetName) uses the named charset.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 67
InputStreamReader
• Methods

Modifier
Method Description
and Type

It closes the stream and releases


void close() any system resources associated
with it.

It returns the name of the character


String getEncoding() encoding being used by this
stream.
int read() It reads a single character.
read(char[] cbuf, int It reads characters into a portion of
int
offset, int length) an array.

It tells whether this stream is ready


boolean ready()
to be read.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 68
InputStreamReader
• Example
public class InputStreamReaderExample {
public static void main(String[] args) {
try {
InputStream stream = new FileInputStream("file.txt");
Reader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 69
Serialization and Deserialization
• 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.
• Advantages of Java Serialization
• It is mainly used to travel object's state on the network (which is known
as marshaling).

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 70
Serialization and Deserialization
• 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 the 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 implement the
java.io.Serializable interface by default.
• Example
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 71
ObjectOutputStream class
• The ObjectOutputStream class is used to write primitive data types,
and Java objects to an OutputStream.
• Objects that support the java.io.Serializable interface can only be
written to streams.
• Constructor
1) public
creates an ObjectOutputStream that
ObjectOutputStream(OutputStre
writes to the specified OutputStream.
am out) throws IOException {}
• 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 {}
Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 72
ObjectOutputStream class
• Example of Java Serialization
import java.io.*;
class Persist{
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");
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 73
ObjectInputStream class
• Deserialization: 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 creates an ObjectInputStream that
ObjectInputStream(InputStream reads from the specified
in) throws IOException {} InputStream.
• Methods
Method Description
1) public final Object
readObject() throws
reads an object from the input stream.
IOException,
ClassNotFoundException{}
2) public void close() throws
closes ObjectInputStream.
IOException {}
Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 74
ObjectInputStream class
• Example of Java Deserialization
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{

ObjectInputStream in=new ObjectInputStream(new FileInputStrea


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

in.close();
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 75
Serialization
• If a class implements serializable then all its sub classes will also be
serializable.
• Example
import java.io.Serializable;
class Person implements Serializable{
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
class Student extends Person{
String course;
int fee;
public Student(int id, String name, String course, int fee) {
super(id,name);
this.course=course;
this.fee=fee;
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 76
Serialization
• If a class has a reference to another class, all the references must be
Serializable otherwise it will throw NotSerializableException
exception.
class Address{
String addressLine,city,state;
public Address(String addressLine, String city, String state) {
this.addressLine=addressLine;
this.city=city;
this.state=state;
}
}

import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
Address address;//HAS-A
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 77

Serialization
• Java Serialization with the static data member
• If there is any static data member in a class, it will not be
serialized because static is the part of class not object.

class Employee implements Serializable{


int id;
String name;
static String company="SSS IT Pvt Ltd";//it won't be serialized
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
• Java Serialization with array or collection
• In case of array or collection, all the objects of array or collection
must be serializable. If any object is not serialiizable, serialization
will be failed.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 78

Transient Keyword
• Java transient keyword is used in serialization.
• If you define any data member as transient, it will not be serialized.
• Example of Java Transient Keyword
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}
• The age data member of the Student class is declared as transient, its
value will not be serialized.
• If you deserialize the object, you will get the default value for
transient variable.

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 79
Transient Keyword
• Now write the code to serialize the object.
import java.io.*;
class PersistExample{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi",22);//creating object
//writing object into file
FileOutputStream f=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(f);
out.writeObject(s1);
out.flush();

out.close();
f.close();
System.out.println("success");
}
}
• code for deserialization.
import java.io.*;
class DePersist{
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+" "+s.age);
in.close();
}
}

Sukhendu Shekhar Mondal, Assistant Professor, Cooch Behar Government Engineering College 80

You might also like