0% found this document useful (0 votes)
55 views

Chapter 10

The document discusses Java I/O stream classes for reading from and writing to files and other sources. It describes the File and RandomAccessFile classes for accessing files, along with input and output stream classes like FileInputStream. Input streams can read bytes from sources like files and keyboards using methods like read(). The System.in object represents keyboard input, while FileInputStream can be used to read bytes from a file.

Uploaded by

Shubham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Chapter 10

The document discusses Java I/O stream classes for reading from and writing to files and other sources. It describes the File and RandomAccessFile classes for accessing files, along with input and output stream classes like FileInputStream. Input streams can read bytes from sources like files and keyboards using methods like read(). The System.in object represents keyboard input, while FileInputStream can be used to read bytes from a file.

Uploaded by

Shubham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Chapter 10

JAVA BINARY (I/O) STREAM CLASSES

Files are the primary source and destination for storing the data contained in
programs. Java provides the java.io package for performing I/O operations. The
java.io package includes the File class, which provides support for creating various
files and directories. The File class describes the properties of a File object and
provides various methods for storing and retrieving the contents from a file.
The File class in the java.io package provides various methods to access the
properties of a file or a directory, such as file permissions, date and time of creation,
and path of a directory. A directory stores files and other directories in it and is
created using the File class. An object of the File class represents a file or a directory.
You can use the following constructors to create an instance of the File class:
􀀃File(File dirObj, String filename): Creates a new instance of the File class. The
dirObj argument is a File object that specifies a directory. The filename argument
specifies the name of the file.
􀀃File(String directoryPath): Creates a new instance of the File class. The directoryPath
argument specifies the path of the file.
􀀃File(String directoryPath, String filename): Creates a new instance of the File class.
The argument directoryPath specifies the path of the file, and the filename argument
specifies the name of the file. The various methods of the File class are:
􀀃String getName(): Retrieves the name of the specified file.
􀀃String getParent(): Retrieves the name of the parent directory.
􀀃String getPath(): Retrieves the path of the specified file.
􀀃String[] list(): Displays the list of files and directories inside the specified directory.

You can use the following code to access the properties of a file or a directory:
import java.io.*;
class Files
{
public static void main(String args[])throws NullPointerException
{
String dirName = "C:/Test";
File f = new File(dirName, "work.txt");
File f3 = new File(dirName, "renFile.txt");
System.out.println("File name is:" +f.getName());
System.out.println("Path of the file is:" +f.getPath());
System.out.println("Parent directory is:" +f.getParent());

System.out.println("Listing the contents of directory");


File f1 = new File(dirName);
String s[] = f1.list();
the Test directory. */
for(int i = 0;i<s.length;i++)
{
contained in the Test directory. */
File f2 = new File("\t" +dirName+ "/" +s[i]);
the if block of the loop otherwise enters the else block. */
if(f2.isDirectory())
{
System.out.println("\t" +s[i] + "is a directory");
}
else
{
System.out.println("\t" +s[i] + "is a file");
}

}}}

In the preceding code, an instance of the work.txt file is created using the File class.
The Files class shows information such as path and parent directory of the work.txt file.
If the work.txt file contains text, the File class lists the contents of the file.

Random access files enable you to access the contents of a file in a non-sequential
manner. These files enable you to read and write text and bytes to any location in a
file. Random access files are not derived from any InputStream or OutputStream. On
the other hand, these files implement the DataInput and DataOutput interfaces,
which define the basic I/O operations.

You access the random files in Java by using the RandomAccessFile class. The
constructor throws FileNotFoundException, if the RandomAccessFile class is unable
to retrieve the name of the file to be created. You can use the following constructors
to create an instance of the RandomAccessFile class:
􀀃RandomAccessFile(File fileObj, String mode): Creates an instance of the random
access file. The argument fileObj specifies the name of the file to be opened as a File
object. The mode argument specifies the access permissions assigned to a file. The mode
argument can accept the following values:
􀀃 r: Opens a file in the read-only mode.
􀀃 rw: Opens a file in the read/write mode.
􀀃 rws: Opens a file in the read/write mode. The rws mode ensures that each update made
to the file data or metadata is immediately updated to the storage device, such as hard
disk. Metadata is defined as a component of data that provides information about data,
such as name, content, and
quality of data.
􀀃 rwd: Opens a file in the read/write mode. The rwd mode ensures that each update made
to the file data is immediately updated to the underlying storage device.

􀀃RandomAccessFile(String name, String mode): Creates an instance of the random


access file. The name argument specifies the name of a file and the mode argument
specifies the access permissions assigned to the file. The methods of the
RandomAccessFile class throw IOException. Some of the methods of the
RandomAccessFile class are:
􀀃 void close() throws IOException: Closes the random access file and releases the
system resources, such as streams and file pointers associated with the file.
􀀃long getFilePointer() throws IOException: Retrieves the current position of
the file pointer in the specified file.
􀀃long length() throws IOException: Retrieves the length of the specified file.
􀀃void seek(long position) throws IOException: Sets the current location of
the file pointer at the specified position.
􀀃int skipBytes(int n) throws IOException: Ignores the number of bytes from
a file specified by the n argument.
You can use the following code to create the TestRandomFile that shows how to use

the RandomAccessFile class:

import java.io.*;
public class TestRandomFile
{
public static void main(String args[])
{
RandomAccessFile file=null;
try
{
file=new RandomAccessFile("work.txt","rw");
file.writeInt(85);
file.writeChar('V');
file.seek(0);
System.out.println(file.readInt());
System.out.println(file.readChar());
file.seek(file.length());
file.writeBoolean(true);
file.seek(3);
System.out.println(file.readBoolean());
file.close();
} catch(IOException e)
{
System.out.println("Exception: " +e);
}

}}

In the preceding code, the TestRandomFile class opens the work.txt file in the
read/write mode. If the file does not exist, then the RandomAccessFile class creates
the specified file. The write() method of the RandomAccessFile class is used to write
in the work.txt file. The read() method of the RandomAccessFile class is used to read
from the work.txt file and displays the values on the screen using the System.out.println()
method.

A Java program uses streams to either read data items from a source or to write data
items to a destination. I/O operations consist of two parts, data that is entered into a
program through an input source, such as a keyboard and the processed data that is
returned through an output source, such as a monitor. Programs in Java perform I/O
operations with the help of streams. A stream is a passage through which the data items
flow from a source, such as a program, to a destination, such as a file.

Stream sources include files and memory buffers, and stream destinations include the
same entities as stream sources and other entities, such as monitor. In an input stream,
data items flow from the source. Similarly, in an output stream data items flow to a
destination. Input stream refers to the flow of data into a program and output stream
refers to the flow of data out of the program.

In Java, the java.io package consists of various I/O stream classes and interfaces that
support I/O operations, such as reading from a file or keyboard and writing to a file or
monitor. Streams in Java are of two types, byte streams and character streams. The basic
unit of a byte stream is a byte, and the basic unit of a character stream is a Unicode
character.

Input streams are the byte streams that read data in the form of bytes. Java provides the
InputStream class to perform input operations. The InputStream class is an abstract class
that enables its subclasses to read data from different sources, such as a file and keyboard
and displays the data on the monitor. Some of the methods of the InputStream class are:
􀀃int read(): Reads the next byte of data from an input stream. It returns –1 if it
encounters the end of a stream.
􀀃int read(byte b[]): Reads the number of bytes from the array specified by the b[]
argument. The read() method returns –1 when the end of the file is encountered.
􀀃int read(byte b[], int offset, int length) throws IOException: Reads the number of bytes
from the array specified by the b[] argument. The argument offset specifies the starting
position for the read operation, and length specifies the number of bytes to be read. The
read() method returns –1 when
the end of the file is encountered.
􀀃available(): Returns the total number of bytes available for reading in a stream.
􀀃long skip(long n) throws IOException: Ignores the specified number of bytes from an
input stream.
􀀃mark(int nbyte): Places a mark at the current point in the input stream and this mark
remains until the specified data bytes are read.
􀀃reset(): Places the file pointer to the previously set mark or at the beginning of the
stream.

System.in Object
The System class in the java.lang package has a static member variable, in that
refers to the keyboard. The in variable is an instance of the InputStream class and is
used to read data from the keyboard. You can use the following code to create the
Testin class that uses System.in object to read a line of text from the keyboard:
public class Testin
{
public static void main(String args[])
{
byte buffer[]=new byte[80];
System.out.println("Type the text to be displayed ");
try
{
System.in.read(buffer);
} catch(Exception e)
{
System.out.println("Exception: "+e.toString());
}
String str=new String(buffer);
System.in.read() method. */
System.out.println(str);
}
}
In the preceding code, the Testin class reads the input that a user types from the keyboard
using the System.in.read() method. The input read is displayed on the screen using the
System.out.println() method.

The FileInputStream Class


The FileInputStream class performs file input operations, such as reading data from
a file. The object of the FileInputStream class is used to read bytes of data from
files. You can use the following constructors to create an instance of the
FileInputStream class:
􀀃FileInputStream(File f): Creates a file input stream that connects to an existing file to
be used as data source. The file object f specifies the name of the file to which an input
stream is connected.
􀀃FileInputStream(String s): Creates a file input stream that connects to an existing file to
be used as data source. The path of the file in file system is given by the string argument.
􀀃FileInputStream(FileDescriptor fdobj): Creates a file input stream that connects to an
existing file to be used as data source. The fdObj file descriptor argument represents an
existing connection to the specified file. The FileInputStream object overrides the read()
method to perform reading operation
on files. You can read a single byte or an array of bytes using the read() method.Some of
the methods of the FileInputStream class are:
􀀃public int read(): Reads a byte of data from the input stream.
􀀃public int read(byte b[], int offset, int length): Reads the specifiednumber of bytes of
data from the specified byte array. The offset argumentspecifies the starting position for
reading the data from a file.
􀀃public long skip(long n) throws IOException: Ignores the specified numberof bytes of
data from an input stream.

You can use the following code to create the TestFileInput class to implement the
FileInputStream class:
import java.io.*;
public class TestFileInput
{
public static void main(String args[])
{
byte buffer[]=new byte[100];
try
{
FileInputStream class. */
FileInputStream file=new FileInputStream("filein.txt");
file.read(buffer,0,50);
} catch(Exception e)
{
System.out.println("Exception: "+e.toString());
}
String str=new String(buffer);
System.out.println(str);
}}
In the preceding code, the TestFileInput class creates an instance of the
FileInputStream class to read data from the existing file, filein.txt file. If the file does
not exist, then the program displays a run-time error. The TestFileInput class
displays the contents of the filein.txt file on the screen.

The BufferedInputStream Class


The BufferedInputStream class accepts data from other input streams and stores it in a
memory buffer. The input stream reads data when presented in the specified data format,
such as the ByteArrayInputStream class reads data from a byte array. On the other hand,
the BufferedInputStream class reads data specified in any data format. A buffer stores the
bytes of data and enables you to perform I/O operations on various data bytes
simultaneously. The BufferedInputStream class supports
read(), skip(), mark(), and reset() methods. You can use the following constructors to
create an instance of the BufferedInputStream class:
􀀃BufferedInputStream(InputStream is): Creates an input stream and adds a buffer to it.
The default size of the buffer is 512 bytes.
􀀃BufferedInputStream(InputStream is, int size): Creates an input stream and adds a
buffer of size specified by the size argument.
Using the DataInputStream Class
The DataInputStream class is used to read primitive data types, such as int, float, and
double from an input stream. You can use the following constructor to create an instance
of the DataInputStream class:
DataInputStream(InputStream in): Creates a DataInputStream that uses the specified
InputStream.
Some of the methods of the DataInputStream class are:
􀀃public final int read(byte b[]): Retrieves a byte of input from the input
stream.
􀀃public final int read(byte b[], int offset, int length): Reads the
specified number of bytes of data from the specified byte array. The offset
argument specifies the starting position for reading the data.
􀀃public final int readInt(): Retrieves an integer from the input stream.
􀀃public final String readLine(): Retrieves a String from the input stream.
Accessing Files Using the OutputStream Class
OutputStreams are byte streams that write data in the form of bytes. Java provides the
OutputStream class to perform output operations, such as writing to a file or screen. The
OutputStream class is an abstract class that enables its subclasses to write data to a file or
screen.
Some of the methods of the OutputStream class are:
􀀃 write(int b): Writes the specified byte to a file.
􀀃write(byte b[]): Writes an array of bytes specified by the b argument to a file.
􀀃write(byte b[], int offset, int length): Writes an array of bytes specified by the b
argument to a file. The offset argument determines the starting position for the byte array.
The length argument specifies the number of bytes to be written.
􀀃close(): Closes the byte output stream.
􀀃flush(): Clears the buffers by removing any buffered output written on thedisk.
The FileOutputStream Class
The FileOutputStream class is used to perform file output operations, such as writing to a
file. An object of the FileOutputStream class is used to write bytes of data to a data file.
You can use the following constructors to create an instance of the FileOutputStream
class:
􀀃FileOutputStream(File f): Creates a File stream that connects to an existing file to be
used as destination for data. The File object is used to represent the required data file.
􀀃FileOutputStream(String s): Creates a File stream that connects to an existing file to be
used as destination for data. The string argument provides the complete path of the file in
the file system.
􀀃FileOutputStream(File f, boolean b): Creates a File stream that connects to an existing
file described by the file object. The true value for the Boolean argument specifies that
the file is opened in append mode.
􀀃FileOutputStream(String s, boolean b): Creates a File stream that connects an existing
file specified by path s. The true value for the boolean argument specifies that the file is
opened in append mode.
Some of the methods of the FileOutputStream class are:
􀀃public void write(int b): Writes the specified byte b to the output file stream.
􀀃public void write(byte b[], int offset, int length): Writes the total number of bytes
specified by the length argument of the array b to the output file stream, starting from the
offset position.
You can use the following code to create the TestFileOutput class that shows how to
use the FileOutputStream class:
import java.io.*;
public class TestFileOutput
{
public static void main(String args[])
{
byte buffer[]=new byte[100];
try
{
System.in.read(buffer, 0, 100);
} catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
try
{
FileOutputStream fout = new FileOutputStream("text.txt");
fout.write(buffer);
} catch(FileNotFoundException fnfe)
{
System.out.println("Exception: "+fnfe.toString());
}
catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
}
}
In the preceding code, the TestFileOutput class reads data from the keyboard and stores
it in the text.txt file.

The BufferedOutputStream Class


The BufferedOutputStream class creates a buffer in the memory and attaches this
buffer to the output stream. This buffer stores data bytes and sends multiple data
bytes in just one I/O operation. You can use the following constructors to create an
instance of the BufferedOutputStream class:
􀀃BufferedOutputStream(OutputStream os): Creates an output stream and adds a buffer to
it. The default size of the buffer is 512 bytes.
􀀃BufferedOutputStream(OutputStream os, int buflen): Creates an output stream and adds
a buffer of size specified by the buflen integer variable. The BufferedOutputStream class
contains the following methods:
􀀃public void write(int b): Writes the specified byte to the buffered output stream.
􀀃public void write(byte b[], int offset, int len): Writes the number of bytes from the b[]
into the buffered output stream. The argument offset specifies the starting position for the
write operation and length specifies the number of bytes to be written.
􀀃public void flush(): Writes all the bytes of data that are present in the buffer to the
destination output device, such as a file.
You can use the following code to create the TestBufferedOutput class that shows
how to use the BufferedOutputStream class:
import java.io.*;
public class TestBufferedOutput
{
public static void main(String args[])
{
String str="Creating a program using the BufferedOutputStream. ";
byte buffer[]=str.getBytes();
BufferedOutputStream br = new BufferedOutputStream(System.out);
try
{
br.write(buffer,0,50);
br.flush();
} catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
}
}
In the preceding code, the TestBufferedOutput class initializes the str string and
stores the byte array in the buffered output stream. The class displays the output on
the screen using the write() method of the BufferedOutputStream class.
The FileReader Class
The FileReader class is used for reading characters from a file, but it does not define any
methods of its own. It derives all methods from its base classes, such as the Reader and
InputStreamReader classes. The FileReader class has various constructors. The syntax of
one of the constructor of the FileReader class is:
FileReader(String FileName)
In the preceding syntax, filename is the full path name of the file to be read. The
constructor of the FileReader class may throw the FileNotFoundException exception in
certain conditions, which are:
􀀃The fileObj object does not exist.
􀀃The fileObj object is not a File class object, but a directory object.
􀀃The fileObj object cannot be opened for reading.
The syntax of another constructor of the FileReader class is:
FileReader(File fileObj)

In the preceding syntax, a new FileReader object is constructed where fileObj is the File
Object that specifies the file to read the content from. The constructor of the FileReader
class may throw the FileNotFoundException exception in certain conditions, which are:
􀀃The fileObj object does not exist.
􀀃The fileObj object is not a File class object, but a directory object.
􀀃The fileObj object cannot be opened for reading.
You can use the following code to use the FileReader class to read content from a file:
import java.io.*;
public class TestFileReader
{
public static void main(String args[])
{
try
{
File file=new File("Name.txt");
FileReader f=new FileReader(file);
int ch;
while((ch=f.read())!=-1) //Loop till end of file.
{
System.out.print((char)ch);
}
}
catch(FileNotFoundException fnfe)
{
System.out.println("Exception: "+fnfe.toString());
}
catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
} //End of main()
}
In the preceding code, the f object reads the Name.txt file that already exists by using
the read() method. The read() method of the FileReader class reads one character
at a time until the end of file is reached and then prints it on the standard output
screen. The following figure shows the content of the Name.txt file:
The BufferedReader Class
The BufferedReader stream reads text from a character input stream and attaches a buffer
to the character input Streams. Buffers allow reading more than one character at a time
and increasing the performance of streams by buffering the input data. The
BufferedReader class allows you to wrap any subclass of the Reader class into a buffered
stream and, therefore increases the performance. The BufferedReader class has various
types of constructors. The syntax of one of the constructors of the
BufferedReader class is:
BufferedReader(Reader StreamObj)
In the preceding syntax, an object of the BufferedReader class is constructed with
the default size of the buffer. The syntax of another constructor of the
BufferedReader class is:
BufferedReader(Reader StreamObj, int BuffSize)
In the preceding syntax, an object of the BufferedReader class is constructed where
the BuffSize parameter specifies the size of the input buffer.
The buffering of a character input stream allows moving forward and backward in the
stream within the available buffer. The mark() and reset() methods implemented in the
BufferedReader class allow file pointer to move forward and backward in the buffer. You
can use the following code to use the BufferedReader stream to read
data from a stream:
import java.io.*;
public class TestBuffer
{
public static void main(String args[])
{
System.out.print("Please enter a string:");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); //creates an instance of
BufferedReader class
String str=new String();
try
{
str=br.readLine(); //Reads a line of text into str
}
catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
System.out.print("The string entered is: ");
System.out.println(str);
} //End of main()
}
In the preceding code, the br object of the BufferedReader class is created and it
buffers the text written at the command prompt. The readLine() method of the
BufferedReader class reads a line of text at a time.
The FileWriter Class
The FileWriter class writes character data to a file, but does not define any methods of
its own. It derives all methods from its base classes, such as the Writer and the
OutputStreamReader classes. The FileWriter class has various constructors. The
following table lists various constructors of the FileWriter class:
All the constructors of the FileWriter class throw the IOException exception in
certain conditions, which are:
􀀃The named file cannot be opened.
􀀃The named file exists, but is not an object of the File class.
􀀃The named file does not exist and cannot be created.
You can use the following code to write to a file using the write() method of the
FileWriter class:
import java.io.*;
public class TestFileWriter
{
public static void main (String args[])
{
String str="Character Stream Classes in Java";
try
{
FileWriter fout = new FileWriter("stream.txt" );
fout.write(str, 0, str.length() );
fout.close();
}
catch (IOException ioe)
{
System.out.println("Exception: " + ioe.toString());
}
}
}
In the preceding code, the FileWriter class writes to the stream.txt file. Thewrite() method
of the FileWriter class writes the complete text of the str objectinto the stream.txt file.
The following figure shows the content of the stream.txtfile after the execution of the
preceding code:
The BufferedWriter Class
The BufferedWriter class extends the Writer class and writes text to a character
output stream. The BufferedWriter stream attaches a buffer to the character output
Streams. Buffer allows writing more than one character at a time. Buffer reduces the
number of times data is written to the character output stream and therefore, increases the
performance of the stream. The BufferedWriter class allows you to wrap any subclass of
the Writer class into a buffered stream and increases its performance. The BufferedWriter
class has various constructors. The syntax of one
of the constructors of the BufferedWriter class is:
BufferedWriter(Writer outputStream)
In the preceding syntax, an object of the BufferedWriter class is constructed that uses the
output buffer of default size. The syntax of another constructor of the BufferedWriter
class is:
BufferedWriter(Writer outputStream, int bufSize)
In the preceding syntax, an object of the BufferedWriter class is constructed where the
bufSize variable specifies the size of the output buffer. It throws the
IllegalArgumentException exception if the value of the bufSize variable is less than
or equal to 0.
You can use the following code to write to a file using the write() method of the
BufferedWriter class:
import java.io.*;
public class TestBWriter
{
public static void main(String args[])
{
int ch;
BufferedWriter bw=null;
System.out.print("Enter text(terrminate by pressing ctrl +
z):");
try
{
bw=new BufferedWriter(new FileWriter("buffer.txt"));
while((ch=System.in.read())!=-1) //Loop till end of
file.
{
bw.write(ch);
}
bw.flush();
}
catch(IOException ioe)
{
System.out.println("Exception: "+ioe.toString());
}
}
}
The transient keyword
The data members of a class that are not required to be serialized are declared as
transient. The serialization process ignores the transient variables. The syntax of
declaring a variable as transient is:
transient String password;
Using the ObjectInputStream Class for I/O Operations
The ObjectInputStream class extends the InputStream class and implements the
ObjectInput interface. The ObjectInputStream stream deserializes the primitive data and
objects that are written using the ObjectOutputStream stream.
You can use the following code to read an object from a file using the
ObjectInputStream class:
//Code to deserialize a Date object.
import java.io.*;
import java.util.Date;
public class TestObjectInput
{
public static void main(String args[]) throws
IOException,ClassNotFoundException
{
FileInputStream fis=new FileInputStream("myfile.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
String str=(String)ois.readObject();
Date date=(Date)ois.readObject();
System.out.println(str+date);
}
}
A class implements the Serializable interface in order to serialize its objects. The class
that implements the Serializable interface may be a user-defined class. The
writeObject() method is used to write an object of the serialized class, and the
readObject() method is used to read the serialized object. You can use the following
code to define the Employee class that implements the Serializable interface:

You might also like