Java Features –IO
Package
Manimala K
Assistant Professor
Department of computer Science and Engineering
Government College of Engineering
Salem
Java IO Package
• The package [Link] contains the classes that
handle fundamental input and output operations
in Java. The I/O classes can be grouped as
follows:
– Classes for reading input from a stream of data.
– Classes for writing output to a stream of data.
– Classes that manipulate files on the local file
system.
– Classes that handle object serialization.
• The [Link] package contains nearly every class
need to perform input and output (I/O) in Java.
• All these streams represent an input source and
an output destination.
Java IO Package
• The stream in the [Link] package
supports many data such as primitives,
object, localized characters, etc.
• Stream: A stream can be defined as a
sequence of data. There are two kinds of
Streams:
– InputStream − The InputStream is used
to read data from a source.
– OutputStream − The OutputStream is
used for writing data to a destination.
Byte Streams
• Java Input and Output Streams are categorized
into Byte stream and Character Stream.
• Byte Streams are used to perform input and
output of 8-bit bytes.
• Though there are many classes related to byte
streams but the most frequently used classes
are, FileInputStream and FileOutputStream.
• Following is an example which makes use of
these two classes to copy an input file into an
output file:
Byte Streams
Example Program:
import [Link].*;
public class CopyFile {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try { int c;
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");
while ((c = [Link]()) != -1) { [Link](c); }
}
finally {
if (in != null) { [Link](); }
if (out != null) { [Link](); }
}
}
}
Character Streams
• Byte streams are used to perform input and
output of 8-bit bytes, whereas
Character streams are used to perform input
and output for 16-bit unicode.
• Though there are many classes related to
character streams but the most frequently used
classes are, FileReader and FileWriter.
• Though internally FileReader uses
FileInputStream and FileWriter uses
FileOutputStream but here the major difference
is that FileReader reads two bytes at a time and
FileWriter writes two bytes at a time.
Character Streams
Example Program:
import [Link].*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try { int c;
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
while ((c = [Link]()) != -1) { [Link](c); }
}
finally { if (in != null) { [Link](); }
if (out != null) { [Link](); }
}
}
}
Hierarchy of Input and Output
Stream Classes
Input and Output Streams
• OutputStream: Java application uses an
output stream to write data to a
destination; it may be a file, an array,
peripheral device or socket.
• 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 class
• OutputStream class: OutputStream class is an
abstract class. It is the super class of all classes
representing an output stream of bytes. An output
stream accepts output bytes and sends them to some
sink.
• Useful methods of OutputStream:
– public void write(int)throws IOExceptionis used to write a
byte to the current output stream.
– public void write(byte[])throws IOExceptionis used to
write an array of byte to the current output stream.
– public void flush() throws IOException flushes the current
output stream.
– public void close() throws IOExceptionis used to close the
current output stream.
OutputStream Hierarchy
InputStream class
• InputStream class: InputStream class is an
abstract class. It is the superclass of all
classes representing an input stream of bytes.
• Useful methods of InputStream:
– public abstract int read() throws IOException
reads the next byte of data from the input
stream. It returns -1 at the end of the file.
– public int available()throws IOException
returns an estimate of the number of bytes that
can be read from the current input stream.
– public void close()throws IOException is used
to close the current input stream.
InputStream Hierarchy
FileOutputStream Class
• FileOutputStream is an output stream used for
writing data to a file
• If you have to write primitive values into a file,
use FileOutputStream class. You can write
byte-oriented as well as character-oriented
data through FileOutputStream class. But, for
character-oriented data, it is preferred to
use FileWriter than FileOutputStream.
• The declaration for [Link]
class:
public class FileOutputStream extends Outp
utStream
FileOutputStream class Methods
• protected void finalize() - It is used to clean up the
connection with the file output stream.
• void write(byte[] ary) - It is used to
write [Link] bytes from the byte array to the file
output stream.
• void write(byte[] ary, int off, int len) - It is used to
write len bytes from the 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 getChannel() - It is used to return the file
channel object associated with the file output stream.
• FileDescriptor getFD() - It is used to return the file
descriptor associated with the stream.
• void close() - It is used to closes the file output
stream.
FileOutputStream Class Example
import [Link];
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\
[Link]");
String s="Welcome to java File Output Stream.";
byte b[]=[Link]();//converting string into byte array
[Link](b);
[Link]();
[Link]("success...");
}
catch(Exception e){[Link](e);}
}
}
FileInputStream Class
• FileInputStream 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. You can
also read character-stream data. But, for
reading streams of characters, it is
recommended to use FileReader class.
• The declaration for
[Link] class:
public class FileInputStream extends Inp
utStream
FileInputStream Class
•
Methods
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 [Link] bytes of data
from the input stream.
• int read(byte[] b, int off, int len) - It is used to read up
to len bytes of data from the input stream.
• long skip(long x) - It is used to skip over and discards x bytes of
data from the input stream.
• FileChannel getChannel() - It is used to return the unique
FileChannel object associated with the file input stream.
• FileDescriptor getFD() - It is used to return the FileDescriptor
object.
• protected void finalize() - It is used to ensure that the close
method is call when there is no more reference to the file input
stream.
• void close() - It is used to closes the stream.
FileInputStream Class Example
import [Link];
public class DataStreamExample {
public static void main(String args[]){
try{ int i=0;
FileInputStream fin=new FileInputStream("D:\\
[Link]");
while((i=[Link]())!=-1)
{ [Link]((char)i); }
[Link]();
}
catch(Exception e){[Link](e);}
}
}
BufferedOutputStream Class
• BufferedOutputStream class 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.
• The syntax for adding the buffer in an
OutputStream: OutputStream os = new
BufferedOutputStream (new
FileOutputStream ("D:\\[Link]"));
BufferedOutputStream class
constructors
• The declaration for
[Link] class: public
class BufferedOutputStream extends
FilterOutputStream
• BufferedOutputStream(OutputStream os) - It
creates the new buffered output stream
which is used for writing the data to the
specified output stream.
• BufferedOutputStream(OutputStream os, int
size) - It creates the new buffered output
stream which is used for writing the data to
the specified output stream with a specified
buffer size.
BufferedOutputStream class
methods
• void write(int b) - It writes the specified
byte to the buffered output stream.
• void write(byte[] b, int off, int len) - It
write the bytes from the specified byte
input stream into a specified byte array,
starting with the given offset
• void flush() - It flushes the buffered output
stream.
BufferedOutputStream class Example
import [Link].*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\
[Link]");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to java Program.";
byte b[]=[Link]();
[Link](b);
[Link]();
[Link]();
[Link]();
[Link]("success");
}
}
BufferedInputStream Class
• BufferedInputStream class is used to read
information from stream. It internally uses buffer
mechanism to make the performance fast.
• The important points about BufferedInputStream
are:
– When the bytes from the stream are skipped or read,
the internal buffer automatically refilled from the
contained input stream, many bytes at a time.
– When a BufferedInputStream is created, an internal
buffer array is created.
• The declaration for [Link]
class: public class BufferedInputStream
extends FilterInputStream
BufferedInputStream Class
Constructors
• BufferedInputStream(InputStream IS) - It
creates the BufferedInputStream and
saves it argument, the input stream IS, for
later use.
• BufferedInputStream(InputStream IS, int
size) - It creates the BufferedInputStream
with a specified buffer size and saves it
argument, the input stream IS, for later
use.
BufferedInputStream Class Methods
• 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 off, int ln) - It read the bytes from the
specified byte input 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 readlimit) - It sees the general contract of the
mark method for the input stream.
• long skip(long x) - It skips over and discards x bytes of data from
the input stream.
• boolean markSupported() - It tests for the input stream to
support the mark and reset methods.
BufferedInputStream Class Example
import [Link].*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream ("D:\\[Link]“);
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=[Link]())!=-1){ [Link]((char)i); }
[Link]();
[Link]();
}
catch(Exception e){[Link](e);}
}
}
SequenceInputStream Class
• SequenceInputStream class is used to read data
from multiple streams. It reads data sequentially
(one by one).
• The declaration for [Link]
class: public class SequenceInputStream extends
InputStream
• SequenceInputStream class Constructors:
• SequenceInputStream(InputStream s1, InputStream
s2) - creates a new input stream by reading the data
of two input stream in order, first s1 and then s2.
• SequenceInputStream(Enumeration e) - creates a
new input stream by reading the data of an
enumeration whose type is InputStream.
SequenceInputStream Class Methods
• int read() - It is used to read the next byte
of data from the input stream.
• int read(byte[] ary, int off, int len) - It is
used to read len bytes of data from the
input stream into the array of bytes.
• int available() - It is used to return the
maximum number of byte that can be read
from an input stream.
• void close() - It is used to close the input
stream.
ByteArrayOutputStream Class
• ByteArrayOutputStream class is used to write
common data into multiple files. In this stream,
the data is written into a byte array which can
be written to multiple streams later.
• The ByteArrayOutputStream holds a copy of
data and forwards it to multiple streams.
• The buffer of ByteArrayOutputStream
automatically grows according to data.
• The declaration for
[Link] class: public
class ByteArrayOutputStream extends
OutputStream
ByteArrayOutputStream Class
Constructors
• ByteArrayOutputStream() - Creates a new
byte array output stream with the initial
capacity of 32 bytes, though its size
increases if necessary.
• ByteArrayOutputStream(int size) -
Creates a new byte array output stream,
with a buffer capacity of the specified
size, in bytes.
ByteArrayOutputStream Class
•
Methods
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 charsetName) - It is used for converting
the content into a string 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, int off, int len) - It is used for writing len bytes
from specified byte array starting from the offset off to the byte
array output stream.
• void writeTo(OutputStream out) - It is used for writing the
complete content of a byte array output stream to the specified
output 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.
ByteArrayInputStream Class
• The ByteArrayInputStream is composed of two
words: ByteArray and InputStream. As the name
suggests, it can be used to read byte array as
input stream.
• ByteArrayInputStream class contains an internal
buffer which is used to read byte array as stream.
In this stream, the data is read from a byte array.
• The buffer of ByteArrayInputStream
automatically grows according to data.
• The declaration for [Link]
class: public class ByteArrayInputStream
extends InputStream
ByteArrayInputStream Class
Constructors
• ByteArrayInputStream(byte[] ary) -
Creates a new byte array input stream
which uses ary as its buffer array.
• ByteArrayInputStream(byte[] ary, int
offset, int len) - Creates a new byte array
input stream which uses ary as its buffer
array that can read up to
specified len bytes of data from an array.
ByteArrayInputStream Class
•
Methods
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, int off, int len) - It is used to read up
to len bytes of data from an array of bytes in the input
stream.
• boolean markSupported() - It is used to test the input
stream for mark and reset method.
• long skip(long x) - It is used to skip the x bytes of input
from the input stream.
• void mark(int readAheadLimit) - It is used to set the
current marked position in the stream.
• void reset() - It is used to reset the buffer of a byte array.
• void close()It is used for closing a
ByteArrayInputStream.
DataOutputStream Class
• DataOutputStream class allows an application
to write primitive Java data types to the
output stream in a machine-independent way.
• Java application generally uses the data
output stream to write data that can later be
read by a data input stream.
• The declaration for [Link]
class: public class DataOutputStream
extends FilterOutputStream implements
DataOutput
DataOutputStream Class Methods
• int size() - It is used to return the number of bytes
written to the data output stream.
• void write(int b) - It is used to write the specified
byte to the underlying output stream.
• void write(byte[] b, int off, int len) - It is used to
write len bytes of data to the output stream.
• void writeBoolean(boolean v) - It is used to write
Boolean to the output stream as a 1-byte value.
• void writeChar(int v) - It is used to write char to
the output stream as a 2-byte value.
• void writeChars(String s) - It is used to
write string to the output stream as a sequence of
characters.
• void writeByte(int v) - It is used to write a byte to
the output stream as a 1-byte value.
DataOutputStream Class Methods
• void writeBytes(String s) - It is used to write string
to the output stream as a sequence of bytes.
• void writeInt(int v) - It is used to write an int to the
output stream
• void writeShort(int v) - It is used to write a short to
the output stream.
• void writeShort(int v) - It is used to write a short to
the output stream.
• void writeLong(long v) - It is used to write a long to
the output stream.
• void writeUTF(String str) - It is used to write a
string to the output stream using UTF-8 encoding
in portable manner.
• void flush() - It is used to flushes the data output
stream.
DataInputStream Class
• DataInputStream class allows an
application to read primitive data from
the input stream in a machine-
independent way.
• Java application generally uses the data
output stream to write data that can later
be read by a data input stream.
• The declaration for
[Link] class:
public class DataInputStream extends Fi
lterInputStream implements DataInput
DataInputStream class Methods
• int read(byte[] b) - It is used to read the
number of bytes from the input stream.
• int read(byte[] b, int off, int len) - It is used to
read len bytes of data from the input stream.
• int readInt() - It is used to read input bytes
and return an int value.
• byte readByte() - It is used to read and return
the one input byte.
• char readChar() - It is used to read two input
bytes and returns a char value.
• double readDouble() - It is used to read eight
input bytes and returns a double value.
DataInputStream class Methods
• boolean readBoolean() - It is used to read
one input byte and return true if byte is non
zero, false if byte is zero.
• int skipBytes(int x) - It is used to skip over x
bytes of data from the input stream.
• String readUTF() - It is used to read
a string that has been encoded using the
UTF-8 format.
• void readFully(byte[] b)- It is used to read
bytes from the input stream and store them
into the buffer array.
• void readFully(byte[] b, int off, int len) - It is
used to read len bytes from the input stream.
FilterOutputStream Class
• FilterOutputStream class implements the
OutputStream class. It provides different
sub classes such as BufferedOutputStream
and DataOutputStream to provide
additional functionality. So it is less used
individually.
• The declaration for
[Link] class: public
class FilterOutputStream extends
OutputStream
FilterOutputStream Class Methods
• void write(int b) - It is used to write the
specified byte to the output stream.
• void write(byte[] ary) - It is used to write
[Link] byte to the output stream.
• void write(byte[] b, int off, int len) - It is used
to write len bytes from the offset 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.
FilterInputStream Class
• FilterInputStream class implements the
InputStream. It contains different sub
classes
as BufferedInputStream, DataInputStrea
m for providing additional functionality.
So it is less used individually.
• The declaration for
[Link] class: public
class FilterInputStream extends
InputStream
FilterInputStream Class Methods
• int available() - It is used to return an estimate 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.
• int read(byte[] b) - It is used to read up to [Link]
bytes of data from the input stream.
• long skip(long n) - It is used to skip over and discards n
bytes of data from the input stream.
• boolean markSupported() - It is used to test if the input
stream support mark and reset method.
• void mark(int readlimit) - It is used to mark the current
position in the input stream.
• void reset() - It is used to reset the input stream.
• void close() - It is used to close the input stream.
ObjectStreamClass
• ObjectStreamClass act as
a Serialization descriptor for class.
This class contains the name and
serialVersionUID of the class.
• ObjectStreamField class
• A description of a Serializable field from
a Serializable class. An array of
ObjectStreamFields is used to declare the
Serializable fields of a class.
• The [Link](String
name) method gets the field of this class by
name.
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().
• Most subclasses will override some of the methods
defined here to provide higher efficiency,
functionality or both.
Constructor:
• protected Writer() - It creates a new character-
stream writer whose critical sections will
synchronize on the writer itself.
• protected Writer(Object lock) - It creates a new
character-stream writer whose critical sections will
synchronize on the given object.
Writer Class Methods
• Writer append(char c) - It appends the specified character
to this writer.
• Writer append(CharSequence csq) - It appends the specified
character sequence to this writer
• Writer append(CharSequence csq, int start, int end) - It
appends a subsequence of the specified character sequence
to this 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.
• abstract void write(char[] cbuf, int off, int len) - It writes a
portion of an array of characters.
• void write(int c) - It writes a single character.
• void write(String str) - It writes a string.
• void write(String str, int off, int len) - It writes a portion of a
string.
Reader Class
• Reader is an abstract class for reading
character streams. The only methods that a subclass
must implement are read(char[], int, int) and close().
Most subclasses, however, will override some of the
methods to provide higher efficiency, additional
functionality, or both.
• Some of the implementation class are BufferedReader,
CharArrayReader, FilterReader, InputStreamReader,
PipedReader, StringReader
Constructors:
• protected Reader() - It creates a new character-stream
reader whose critical sections will synchronize on the
reader itself.
• protected Reader(Object lock) - It creates a new
character-stream reader whose critical sections will
synchronize on the given object.
Reader Class Methods
• abstract void close() - It closes the stream and releases any
system resources associated with it.
• void mark(int readAheadLimit) - It marks the present position
in the stream.
• boolean markSupported() - It tells whether this stream
supports the mark() operation.
• int read() - It reads a single character.
• int read(char[] cbuf) - It reads characters into an array.
• abstract int read(char[] cbuf, int off, int len) - It reads
characters into a portion of an array.
• int read(CharBuffer target) - It attempts to read characters
into the specified 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.
FileWriter Class
• 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.
• The declaration for [Link] class:
public class FileWriter extends
OutputStreamWriter
FileWriter Class
Constructors and Methods :
• FileWriter(String file) - Creates a new file. It gets
file name in string.
• FileWriter(File file) - Creates a new file. It gets
file name in File object.
• 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.
FileReader Class
• 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.
• The declaration for [Link]
class: public class FileReader
extends InputStreamReader
FileReader Class
Constructors and Methods:
• FileReader(String file) - It gets filename
in string. It opens the given file in read mode.
If file doesn't exist, it throws
FileNotFoundException.
• 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.
• 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.
BufferedWriter Class &
Constructors
• BufferedWriter class 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.
• The declaration for [Link] class:
public class BufferedWriter extends Writer
• BufferedWriter(Writer wrt) - It is used to create a
buffered character output stream that uses the
default size for an output buffer.
• BufferedWriter(Writer wrt, int size) - It is used to
create a buffered character output stream that uses
the specified size for an output buffer.
BufferedWriter Class Methods
• 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, int off, int len) - It is used
to write a portion of an array of characters.
• void write(String s, int off, int len)- It is used to
write a portion of a string.
• void flush() - It is used to flushes the input
stream.
• void close() - It is used to closes the input stream.
BufferedWriter Class
Example
import [Link].*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter ("D:\\[Link]");
BufferedWriter buffer = new BufferedWriter(writer);
[Link]("Welcome to java Program.");
[Link]();
[Link]("Success");
}
}
BufferedReader Class & Constructor
• 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
makes the performance fast. It inherits
Reader class.
• The declaration for [Link] class:
public class BufferedReader extends Reader
• BufferedReader(Reader rd) - It is used to create
a buffered character input stream that uses the
default size for an input buffer.
• BufferedReader(Reader rd, int size) - It is used
to create a buffered character input stream that
uses the specified size for an input buffer.
BufferedReader Class methods
• int read() - It is used for reading a single character.
• int read(char[] cbuf, int off, int len) - It is used for
reading characters into a portion of an array.
• boolean markSupported() - It is used to test the input
stream support 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 readAheadLimit) - It is used for marking
the present position in a stream.
• void close() - It closes the input stream and releases any
of the system resources associated with the stream.
BufferedReader Class
Example
import [Link].*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\[Link]");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=[Link]())!=-1){
[Link]((char)i);
}
[Link]();
[Link]();
}
}
Reading data from Console
import [Link].*;
public class BufferedReaderExample{
public static void main(String args[])throws Exceptio
n{
InputStreamReader r=new InputStreamReader
([Link]);
BufferedReader br=new BufferedReader(r);
[Link]("Enter your name");
String name=[Link]();
[Link]("Welcome "+name);
}
}
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.
• The declaration for
[Link] class:
public class CharArrayReader extends R
eader
CharArrayReader class methods
• int read() - It is used to read a single character
• int read(char[] b, int off, int len) - It is used to read
characters into the portion of an array.
• boolean ready() - It is used to tell whether the
stream is ready to read.
• boolean markSupported() - It is used to tell whether
the stream supports mark() operation.
• long skip(long n) - It is used to skip the character in
the input stream.
• void mark(int readAheadLimit) - It is used to mark
the present position in 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.
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. Calling the close() method
on this object has no effect.
• The declaration for
[Link] class:
public class CharArrayWriter extends W
riter
CharArrayWriter Class Methods
• 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 c) - It is used to
append the specified character to the writer.
• CharArrayWriter append(CharSequence csq) - It is
used to append the specified character sequence to
the writer.
• CharArrayWriter append(CharSequence csq, int
start, int end) - It is used to append the subsequence
of a specified character to the writer.
CharArrayWriter Class Methods
• 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 len) - It is used to
write a portion of string to the buffer.
• 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 [Link]
reset()It is used to reset the buffer.
• void close() - It is used to close the stream.
PrintStream Class
• The PrintStream class provides methods
to write data to another stream. The
PrintStream class automatically flushes
the data so there is no need to call flush()
method. Moreover, its methods don't
throw IOException.
• The declaration for [Link]
class: public class PrintStream extends
FilterOutputStream implements
Closeable. Appendable
PrintStream Class Methods
• 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.
• void println(boolean b) - It prints the specified boolean
value and terminates the line.
PrintStream Class Methods
• 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.
PrintStream Class Methods
• 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.
• void println() - It terminates the line only.
• void printf(Object format, Object... args) - It writes
the formatted string to the current stream.
• void printf(Locale l, Object format, Object... args) - It
writes the formatted string to the current stream.
• void format(Object format, Object... args) - It writes
the formatted string to the current stream using
specified format.
• void format(Locale l, Object format, Object... args) - It
writes the formatted string to the current stream
using specified format.
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.
• The declaration for [Link]
class:
public class PrintWriter extends Writer
PrintWriter Class Methods
• 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.
• PrintWriter append(char c) - It is used to append
the specified character to the writer.
• PrintWriter append(CharSequence ch) - It is used to
append the specified character sequence to the
writer.
• PrintWriter append(CharSequence ch, int start, int
end) - It is used to append a subsequence of
specified character to the writer.
PrintWriter Class Methods
• boolean checkError() - It is used to flushes the
stream and check its error state.
• protected void setError() - It is used to indicate
that an error occurs.
• protected void clearError() - It is used to clear the
error state of a stream.
• PrintWriter format(String format, Object... args) -
It is used to write a formatted string to the writer
using specified arguments and format 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.
OutputStreamWriter Class
• 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. The resulting
bytes are then accumulated in a buffer before being
written into the underlying output stream.
• The characters passed to write() methods are not
buffered. We optimize the performance of
OutputStreamWriter by using it with in a
BufferedWriter so that to avoid frequent converter
invocation.
OutputStreamWriter Class
Constructor
• OutputStreamWriter(OutputStream out) - It
creates an OutputStreamWriter that uses the
default character encoding.
• OutputStreamWriter(OutputStream out, Charset
cs) - It creates an OutputStreamWriter that uses
the given charset.
• OutputStreamWriter(OutputStream out,
CharsetEncoder enc) - It creates an
OutputStreamWriter that uses the given charset
encoder.
• OutputStreamWriter(OutputStream out, String
charsetName) - It creates an
OutputStreamWriter that uses the named
charset.
OutputStreamWriter Class
Methods
• void close() - It closes the stream, flushing it
first.
• void flush() - It flushes the stream.
• String getEncoding() - It returns the name of the
character encoding being used by this stream.
• void write(char[] cbuf, int off, int len) - It writes a
portion of an array of characters.
• void write(int c) - It writes a single character.
• void write(String str, int off, int len) - It writes a
portion of a string.
InputStreamReader Class &
Constructor
• An InputStreamReader is a bridge from byte streams to
character streams:
• It reads bytes and decodes them into characters using a
specified charset. The charset that it uses may be specified
by name or may be given explicitly, or charset may be
accepted.
• InputStreamReader(InputStream in) - It creates an
InputStreamReader that uses the default charset.
• InputStreamReader(InputStream in, Charset cs) - It
creates an InputStreamReader that uses the given charset.
• InputStreamReader(InputStream in, CharsetDecoder dec) -
It creates an InputStreamReader that uses the given
charset decoder.
• InputStreamReader(InputStream in, String charsetName) -
It creates an InputStreamReader that uses the named
charset.
InputStreamReader Class Methods
• void close() - It closes the stream and
releases any system resources associated
with it.
• String getEncoding() - It returns the name of
the character encoding being used by this
stream.
• int read() - It reads a single character.
• int read(char[] cbuf, int offset, int length) - It
reads characters into a portion of an array.
• boolean ready() - It tells whether this stream
is ready to be read.
PushbackInputStream Class
• PushbackInputStream class overrides
InputStream and provides extra
functionality to another input stream.
• It can unread a byte which is already read
and push back one byte.
• The declaration for
[Link] class:
public class PushbackInputStream
extends FilterInputStream
PushbackInputStream Class Methods
• 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.
• 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.
PushbackReader Class
• PushbackReader class is a character
stream reader. It is used to pushes back a
character into stream and overrides the
FilterReader class.
• The declaration for
[Link] class: public
class PushbackReader extends
FilterReader
PushbackReader Class Methods
• int read() - It is used to read a single character.
• void mark(int readAheadLimit) - It is used to mark the
present position in a stream.
• boolean ready() - It is used to tell whether the stream is
ready to be read.
• boolean markSupported() - It is used to tell whether the
stream supports mark() operation.
• long skip(long n) - It is used to skip the character.
• void unread (int c) - It is used to pushes back the
character by copying it to the pushback buffer.
• void unread (char[] cbuf) - It is used to pushes back an
array of character by copying it to the pushback buffer.
• void reset()- It is used to reset the stream.
• void close() - It is used to close the stream.
StringWriter Class
• StringWriter class 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.
• The declaration for [Link]
class: public
class StringWriter extends Writer
StringWriter Class Methods
• 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 off, int len) - It is used to write the
portion of a string.
• void write(char[] cbuf, int off, int len) - It is used to write the
portion of an array of 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 append(char c)- It is used to append the specified
character to the writer.
• StringWriter append(CharSequence csq) - It is used to append
the specified character sequence to the writer.
• StringWriter append(CharSequence csq, int start, int end) - It is
used to append the subsequence of specified character sequence
to the writer.
• void flush() - It is used to flush the stream.
• void close() - It is used to close the stream.
StringReader Class
• StringReader class 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.
• The declaration for [Link]
class: public
class StringReader extends Reader
StringReader Class Methods
• int read() - It is used to read a single character.
• int read(char[] - cbuf, int off, int len) - It is used to
read a character into a portion of an array.
• boolean ready() - It is used to tell whether the stream
is ready to be read.
• boolean markSupported() - It is used to tell whether
the stream support mark() operation.
• long skip(long ns) - It is used to skip the specified
number of character in a stream
• void mark(int readAheadLimit) - It is used to mark
the mark the present position in a stream.
• void reset() - It is used to reset the stream.
• void close() - It is used to close the stream.
PipedWriter Class & Constructor
• The PipedWriter class is used to
write java pipe as a stream of characters.
This class is used generally for writing text.
Generally PipedWriter is connected to
a PipedReader and used by different threads.
Constructors:
• PipedWriter() - It creates a piped writer that
is not yet connected to a piped reader.
• PipedWriter(PipedReader snk) - It creates a
piped writer connected to the specified piped
reader.
PipedWriter Class Methods
• void close() - It closes this piped output stream and
releases any system resources associated with this
stream.
• void connect(PipedReader snk) - It connects this
piped writer to a receiver.
• void flush() - It flushes this output stream and forces
any buffered output characters to be written out.
• void write(char[] cbuf, int off, int len) - It writes len
characters from the specified
character array starting at offset off to this piped
output stream.
• void write(int c) - It writes the specified char to the
piped output stream.
PipedReader Class & Constructors
• The PipedReader class is used to read the contents of a pipe
as a stream of characters. This class is used generally to read
text.
• PipedReader class must be connected to the
same PipedWriter and are used by different threads.
• Constructors:
• PipedReader(int pipeSize) - It creates a PipedReader so that
it is not yet connected and uses the specified pipe size for the
pipe's buffer.
• PipedReader(PipedWriter src) - It creates a PipedReader so
that it is connected to the piped writer src.
• PipedReader(PipedWriter src, int pipeSize) - It creates a
PipedReader so that it is connected to the piped writer src
and uses the specified pipe size for the pipe's buffer.
• PipedReader() - It creates a PipedReader so that it is not yet
connected.
PipedReader Class Methods
• void close() - It closes this piped stream and
releases any system resources associated with the
stream.
• void connect(PipedWriter src) - It causes this piped
reader to be connected to the piped writer src.
• int read() - It reads the next character of data from
this piped stream.
• int read(char[] cbuf, int off, int len) - It reads up to
len characters of data from this piped stream into
an array of characters.
• boolean ready() - It tells whether this stream is
ready to be read.
FilterWriter Class & Constructor
• FilterWriter class is an abstract class
which is used to write filtered character
streams.
• The sub class of the FilterWriter should
override some of its methods and it may
provide additional methods and fields
also.
Constructor:
• protected FilterWriter(Writer out) - It
creates InputStream class Object
FilterWriter Class Methods
• void close() - It closes the stream, flushing
it first.
• void flush() - It flushes the stream.
• void write(char[] cbuf, int off, int len) - It
writes a portion of an array of characters.
• void write(int c) - It writes a single
character.
• void write(String str, int off, int len) - It
writes a portion of a string.
FilterReader Class & Constructor
• FilterReader is used to perform filtering
operation on reader stream. It is an abstract
class for reading filtered character streams.
• The FilterReader provides default methods
that passes all requests to the contained
stream. Subclasses of FilterReader should
override some of its methods and may also
provide additional methods and fields.
Constructor:
• protected FilterReader(Reader in) - It creates
a new filtered reader.
FilterReader Class Methods
• void close() - It closes the stream and releases
any system resources associated with it.
• void mark(int readAheadLimit) - It marks the
present position in the stream.
• boolean markSupported() - It tells whether this
stream supports the mark() operation.
• boolean ready() - It tells whether this stream is
ready to be read.
• int read() - It reads a single character.
• int read(char[] cbuf, int off, int len) - It reads
characters into a portion of an array.
• void reset() - It resets the stream.
• longs kip(long n) - It skips characters.
File Class
• The File class is an abstract
representation of file and directory
pathname. A pathname can be either
absolute or relative.
• The File class have several methods for
working with directories and files such as
creating new directories or files, deleting
and renaming directories or files, listing
the contents of a directory etc.
File Class Fields
• static String pathSeparator - It is system-
dependent path-separator character,
represented as a string for convenience.
• static char pathSeparatorChar - It is system-
dependent path-separator character.
• static String separator - It is system-
dependent default name-separator character,
represented as a string for convenience.
• static char separatorChar - It is system-
dependent default name-separator character.
File Class Constructors
• File(File parent, String child) - It creates a
new File instance from a parent abstract
pathname and a child pathname string.
• File(String pathname) - It creates a new File
instance by converting the given pathname
string into an abstract pathname.
• File(String parent, String child) - It creates a
new File instance from a parent pathname
string and a child pathname string.
• File(URI uri) - It creates a new File instance
by converting the given file: URI into an
abstract pathname.
File Class Methods
• static File createTempFile(String prefix, String suffix) -
It creates an empty file in the default 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
[Link][]
• boolean canExecute() - It tests whether the application
can execute the file denoted by this abstract pathname.
• 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.
File Class Methods
• 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.
• Path toPath() - It returns a [Link] object
constructed from the this abstract path.
• URI toURI() - It constructs a file: URI that
represents this abstract pathname.
File Class Methods
• 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.
RandomAccessFile Class & Constructors
• This class is used for reading and writing to random
access file. A random access file behaves like a
large array of bytes. There is a cursor implied to the array
called file pointer, by moving the cursor we do the read
write operations.
• If end-of-file is reached before the desired number of byte
has been read than EOFException is thrown. It is a type
of IOException.
Constructors:
• RandomAccessFile(File file, String mode) - Creates a
random access file stream to read from, and optionally to
write to, the file specified by the File argument.
• RandomAccessFile(String name, String mode) - Creates a
random access file stream to read from, and optionally to
write to, a file with the specified name.
RandomAccessFile Class Methods
• void close() - It closes this random access file stream and
releases any system resources associated with the
stream.
• FileChannel getChannel() - It returns the
unique FileChannel object associated with this file.
• int readInt() - It reads a signed 32-bit integer from this
file.
• String readUTF() - It reads in a string from this file.
• void seek(long pos) - It sets the file-pointer offset,
measured from the beginning of this file, at which the
next read or write occurs.
• void writeDouble(double v) - It converts the double
argument to a long using the doubleToLongBits method in
class Double, and then writes that long value to the file as
an eight-byte quantity, high byte first.
RandomAccessFile Class Methods
• void writeFloat(float v) - It converts the float
argument to an int using the floatToIntBits
method in class Float, and then writes that int
value to the file as a four-byte quantity, high
byte first.
• void write(int b) - It writes the specified byte to
this file.
• int read() - It reads a byte of data from this file.
• long length() - It returns the length of this file.
• void seek(long pos) - It sets the file-pointer
offset, measured from the beginning of this
file, at which the next read or write occurs.
RandomAccessFile Class Example
import [Link];
import [Link];
public class RandomAccessFileExample {
static final String FILEPATH ="[Link]";
public static void main(String[] args) {
try {
[Link](new String(readFromFile (FILEPATH, 0,
18)));
writeToFile( FILEPATH, "I love my country and my people", 31);
}
catch (IOException e) {
[Link]();
}
}
RandomAccessFile Class Example
private static byte[] readFromFile(String filePath,
int position, int size) throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
[Link](position);
byte[] bytes = new byte[size];
[Link](bytes);
[Link](); return bytes;
}
private static void writeToFile(String filePath, String data, int posit
ion)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw")
;
[Link](position);
[Link]([Link]());
[Link]();
}
}