java.io
java.io
Java Input/Output
Java.io package contains all the classes required for input and output operations. Java provides
strong, flexible support for I/O as it relates to files, console and networks.
Java uses the concept of a stream to make I/O operation fast. All these streams represent an
input source and an output destination. The stream in the java.io package supports many data
such as primitives, object, localized characters, etc.
In Java, three standard streams are created for us automatically. All these streams are
attached with the console. 1) System.out: standard output stream 2) System.in: standard
input stream 3) System.err: standard error stream
There are two kinds of Streams –
Byte Streams – provide a convenient means for handling input/output of bytes. It is used
when reading or writing binary data.
Byte streams are defined by using two class hierarchies. At the top two abstract classes:
InputStream and OutputStream. Each of these abstract classes has several concrete
subclasses, that handle various devices, such as disk files, network connection, memory buffer
etc. . The two most important abstract methods are read() and write(). They are overridden
by derived stream classes.
Character Streams – provide a convenient means for handling input/output of characters.
They use Unicode and, therefore, can internationalized.
Character streams are defined by using two class hierarchies. At the top two abstract
classes: Reader and Writer. Each of these abstract classes has several concrete subclasses. The
most important methods are read() and write() which read and write characters of data. These
methods are overridden by derived stream classes.
Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using
these you can store characters, videos, audios, images etc.
Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only.
Byte Streams:
InputStream :
InputStream class is an abstract class. It is the super class of all classes representing an input
stream of bytes.
InputStream is used to read data that must be taken as an input from a source array or file or
any peripheral device. Few important methods are :
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream. It returns -1 at the end
IOException of the file.
2) public int available()throws returns an estimate of the number of bytes that can be read from the
IOException current input stream.
3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy
Method Description
1) public abstract void write(int)throws is used to write a byte to the current output
IOException stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
Method Description
int available() It is used to return the estimated number of bytes that can be read
from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, It is used to read up to len bytes of data from the input stream.
int len)
long skip(long x) It is used to skip over and discards x bytes of data from the input
stream.
FileChannel It is used to return the unique FileChannel object associated with the
getChannel() file input stream.
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.
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("t.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
} }
Java FileOutputStream Class
Java 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.
Method Description
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 ary.length bytes from the byte array to the file
output stream.
void write(byte[] ary, int It is used to write len bytes from the byte array starting at
off, int len) offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
import java.io.*;
class I3
{
public static void main(String s[]) throws IOException
{
FileOutputStream fo = new FileOutputStream("Ofile.txt");
fo.write(84);
String str="his is a string";
byte b[]=str.getBytes();
for(int i=0;i<b.length;i++)
fo.write(b[i]);
fo.write(10);
fo.write(b);
fo.close();
}
}
File :
Although most of the classes defined by java.io. operates on stream but the File class
does not. It deals directly with files and file system. That is, the File class does not specify how
information is retrieved from or stored in files; it describes the properties of a file itself. A File
object is used to obtain or manipulate the information associated with a disk file, such as
permissions, time, date and directory path etc.
import java.io.*;
class I4
{
static void p(String str)
{ System.out.println(str);
}
public static void main(String s[])
{
File fl = new File(s[0]);
p("FileName :"+fl.getName());
p("Path :"+fl.getPath());
p("Abs Path :"+fl.getAbsolutePath());
p("Parent :"+fl.getParent());
p("exist :"+(fl.exists() ? "file exist" : " file doesnot exist"));
p("canWrite :"+(fl.canWrite() ? "yes" : " no "));
p("canRead :"+(fl.canRead() ? "yes" : " no "));
p("isDirectory :"+(fl.isDirectory() ? "yes A folder" : "not a folder"));
p("isFile :"+(fl.isFile() ? "yes a file" : " not a file "));
p("lastModified :"+fl.lastModified());
p("Length :"+fl.length());
}
}
Character Streams – provide a convenient means for handling input/output of
characters. They use Unicode and, therefore, can internationalized.
In Java, characters are stored using Unicode conventions. Character stream automatically
allows us to read/write data character by character. For example FileReader and FileWriter are
character streams used to read from source and write to destination.
Reader :
Reader is an abstract class that defines streaming character input. All of the methods in this
class will throw an IOException on error conditions. .
Writer :
Writer is an abstract class that defines streaming character output. All of the methods in this
class return a void value and throw IOException in the case of errors.
Java Reader
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(). 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, FileReader
abstract int read(char[] cbuf, int off, It reads characters into a portion of an array.
int len)
FileReader :
The FileReader class creates a Reader that we can use to read the contents of a file. Its two
most commonly used constructors are :
FileReader(String filePath)
FileReader(File fileObj)
Constructor
Methods
Modifier Method Description
and Type
abstract write(char[] cbuf, int off, int It writes a portion of an array of characters.
void len)
void write(String str, int off, int len) It writes a portion of a string.
FileWriter :
The FileWriter class creates a Writer that we can use to write the contents on a file. Its most
commonly used constructors are :
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
import java.io.*;
public class FileRead {
for(char c : a)
System.out.print(c); // prints the characters one by one
fr.close();
}
Java 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(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 It is used to create a buffered character input stream that uses
size) the specified size for an input buffer.
Java BufferedReader class methods
Method Description
int read(char[] cbuf, int off, It is used for reading characters into a portion of an array.
int len)
boolean markSupported() It is used to test the input stream support for the mark and reset
method.
boolean ready() It is used to test whether the input stream is ready to be read.
void reset() It repositions the stream at a position the mark method was last
called on this input stream.
void close() It closes the input stream and releases any of the system resources
associated with the stream.
Java BufferedReader Example
In this example, we are reading the data from the text file t.txt using Java BufferedReader class.
import java.io.*;
public class IOBuffRe1
{
public static void main(String args[])throws Exception
{ FileReader fr=new FileReader("t.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1)
{ System.out.print((char)i);
}
br.close();
fr.close();
}}
Reading data from console by InputStreamReader and
BufferedReader
In this example, we are connecting the BufferedReader stream with
the InputStreamReader stream for reading the line by line data from the keyboard.
import java.io.*;
public class IOBuffRe2
{
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);
} }
Another example of reading data from console until user writes stop
In this example, we are reading and printing the data until the user prints stop.
import java.io.*;
public class IOBuffRe3{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(!name.equals("stop"))
{ System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
} }
Java BufferedWriter Class
Java 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.
Class declaration
The declaration for Java.io.BufferedWriter class:
public class BufferedWriter extends Writer
Class constructors
Constructor Description
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, It is used to create a buffered character output stream that uses
int size) the specified size for an output buffer.
Class methods
Method Description
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.
RandomAccessFile(String name, Creates a random access file stream to read from, and
String mode) optionally to write to, a file with the specified name.
Method
Modifier and Method Method
Type
void close() It closes this random access file stream and releases any
system resources associated with the stream.
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 seek(long pos) It sets the file-pointer offset, measured from the begin-
ning of this file, at which the next read or write occurs.
import java.io.IOException;
import java.io.RandomAccessFile;
The objectinputstream class is mainly used to deserialize the primitive data and objects which
are written by using ObjectOutputStream. ObjectInputStream can also be used to pass the
objects between hosts by using a SocketStream. The objects which implement Serializable or
Externalizable interface can only be read using ObjectInputStream. Consider the example in the
last of this topic to read an object from the file which was previously written by using
ObjectOutputStream.
1 public int available() The available() method returns the number of bytes that can be
throws IOException read without blocking.
2 public void close() The close() method closes the input stream. It must be called to
throws IOException release any resource associated with the stream.
3 public void defaultReadObject() The default ReadObject() method reads the non-static and non-
throws transient fields of the current class from this stream. i.e one cannot
IOException, use defaultReadObject() to read the static fields. This may only be
ClassNotFoundException called from the readObject method of the class being desterilized.
You cannot use defaultReadObject() directly.
5 public int read(byte[] buf, int off, The read() method read into an array of bytes. There should be
int len) some bytes present to be read otherwise the method will block.
throws IOException This method takes 3 parameters, a byte array buff into which the
bytes are stored, starting offset off to start reading, Length of bytes
len.
6 public boolean readBoolean() This method reads a Boolean from the stream. It returns true if the
throws IOException byte is non-zero otherwise false
14 public String readLine() The readLine() method reads in a line that has been terminated by
throws IOException a \n, \r, \r\n or EOF.
NO Method Description
1 public int available() throws IOException The available() method returns the number
of bytes that can be read without blocking.
2 public void close() throws IOException The close() method closes the input stream.
It must be called to release any resource
associated with the stream.
3 public void defaultReadObject() throws The default ReadObject() method reads the
IOException, ClassNotFoundException non-static and non-transient fields of the
current class from this stream. i.e one
cannot use defaultReadObject() to read the
static fields. This may only be called from
the readObject method of the class being
desterilized. You cannot use
defaultReadObject() directly.
5 public int read(byte[] buf, int off, int The read() method read into an array of
len) throws IOException bytes. There should be some bytes present
to be read otherwise the method will block.
This method takes 3 parameters, a byte
array buff into which the bytes are stored,
starting offset off to start reading, Length of
bytes len.
6 public boolean readBoolean() throws This method reads a Boolean from the
IOException stream. It returns true if the byte is non-zero
otherwise false
7 public byte readByte() throws IOException The readByte() method reads an 8-bit byte.
8 public char readChar() throws IOException The readChar() method reads a 16-bit char.
10 public float readFloat() throws IOException The readFloat() method reads a 32-bit float.
11 Public int readInt() throws IOException The readInt() method reads a 32-bit int.
12 public long readLong() throws IOException The readLong() method reads a 64-bit float.
13 Public short readShort() throws IOException The readShort() method read 16 bit short.
14 public String readLine() throws IOException The readLine() method reads in a line that
has been terminated by a \n, \r, \r\n or EOF.
class ObjWr
{
public static void main(String s[])
{
try{
Student obj = new Student("Sumit","100");
FileOutputStream fis = new FileOutputStream("tt.txt");
ObjectOutputStream oos= new ObjectOutputStream(fis);
oos.writeObject(obj);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Read Object from file :
import java.io.*;
class Student implements Serializable
{
String name; String id;
Student(String n,String i)
{ name=n; id =i;
}
void show()
{ System.out.println(name+":"+id); }
}
class ObjrT
{
public static void main(String s[])
{
try{
ObjectInputStream ois= new ObjectInputStream(new FileInputStream("tt.txt"));
Student obj=null;
obj=(Student)ois.readObject();
obj.show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}