Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

File handling in JAVA

• File Handling is an integral part of any programming language as file


handling enables us to store the output of any particular program in a
file and allows us to perform certain operations on it.
• In Java, with the help of File Class, we can work with files. This File
Class is inside the java.io package. The File class can be used by
creating an object of the class and then specifying the name of the file.
import java.io.File;

class EG{
public static void main(String[] args)
{

// File name specified


File obj = new File("myfile.txt");
System.out.println("File Created!");
}
}
Streams in JAVA
• In Java, the concept Stream is used in order to perform I/O operations
on a file.
• Streams in Java
• In Java, a sequence of data is known as a stream.
• This concept is used to perform I/O operations on a file.
• There are two types of Streams you can use to interact with files:
1.Character Streams
2.Byte Streams
• For each of the above stream types, there are several supporting
classes shipped with Java
Character Streams
• Character Streams are used to read or write the characters data type. Let's look
at the most commonly used classes. All of these classes are defined under the
java.io package.
• Here are some classes you should know that can be used to read character data:
Reader: An abstract class to read a character stream.
InputStreamReader: Class used to read the byte stream and converts to
character stream.
FileReader: A class to read the characters from a file.
BufferedReader: This is a wrapper over the Reader class that supports
buffering capabilities. In many cases this is the most preferable class to read
data because more data can be read from the file in one read() call,
reducing the number of actual I/O operations with the file system.
And here are some classes you can use to write character data to a file:

• Writer: This is an abstract class to write the character streams.


• OutputStreamWriter: This class is used to write character streams and
also convert them to byte streams.
• FileWriter: A class to actually write characters to the file.
• BufferedWriter: This is a wrapper over the Writer class, which also
supports buffering capabilities. This is the most preferable class to
write data to a file since more data can be written to the file in one
write() call. And like the BufferedReader, this reduces the number of
total I/O operations with the file system.
Byte Streams
• Byte Streams are used to read or write byte data with files. This is
different from before in the way they treat the data. Here you work
with raw bytes, which could be characters, image data, Unicode data
(which takes 2 bytes to represent a character), etc.
Here are the classes used to read the byte data:
• InputStream: An abstract class to read the byte streams.
• FileInputStream: A class to simply read bytes from a file.
• BufferedInputStream: This is a wrapper over InputStream that
supports buffering capabilities. As we saw in the character streams,
this is a more efficient method than FileInputStream.
And here are the classes used to write the byte data:
• OutputStream: An abstract class to write byte streams.
• FileOutputStream: A class to write raw bytes to the file.
• ByteOutputStream: This class is a wrapper over OutputStream to
support buffering capabilities. And again, as we saw in the character
streams, this is a more efficient method than FileOutputStream
thanks to the buffering.
• Files are opened by creating objects of these stream classes that inherit
from classes InputStream, OutputStream, Reader and Writer,
respectively.
• Thus, the methods of these stream classes can all be applied to file
streams as well.
• To perform input and output of data types, objects of class
ObjectInputStream, DataInputStream, ObjectOutputStream and
DataOutputStream will be used together with the byte-based file
stream classes FileInputStream and File-OutputStream.
Formatted Data-Streams: DataInputStream &
DataOutputStream
• The DataInputStream and DataOutputStream can be stacked on top
of any InputStream and OutputStream to parse the raw bytes so as to
perform I/O operations in the desired data format, such as int and
double.
• To use DataInputStream for formatted input, you can chain up the
input streams as follows:
DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("in.dat")));
• provides methods to read formatted primitive data and String, such as:
public final int readInt() throws IOExcpetion; // Read 4 bytes and convert into int
public final double readDoube() throws IOExcpetion; // Read 8 bytes and convert into double
public final byte readByte() throws IOExcpetion;
public final char readChar() throws IOExcpetion;
public final short readShort() throws IOExcpetion;
public final long readLong() throws IOExcpetion;
public final boolean readBoolean() throws IOExcpetion; // Read 1 byte. Convert to false if zero
public final float readFloat() throws IOExcpetion;
public final String readLine() throws IOException; // Read a line (until newline), convert each byte into
//a char - no unicode support.
• Similarly, you can stack the DataOutputStream as follows:
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("out.dat")));
• provides methods to write formatted primitive data and String. For
examples,
public final void writeInt(int i) throws IOExcpetion; // Write the int as 4 bytes
public final void writeFloat(float f) throws IOExcpetion;
public final void writeDoube(double d) throws IOExcpetion; // Write the double as 8
bytes
public final void writeByte(int b) throws IOExcpetion; // least-significant byte
public final void writeShort(int s) throws IOExcpetion; // two lower bytes
public final void writeLong(long l) throws IOExcpetion;
public final void writeBoolean(boolean b) throws IOExcpetion;
public final void writeChar(int i) throws IOExcpetion;
The following program writes some primitives to a disk file. It then
reads the raw bytes to check how the primitives were stored. Finally, it
reads the data as primitives.
import java.io.*; // Read primitives
class Main try (DataInputStream in = new DataInputStream( new
{ BufferedInputStream( new FileInputStream(filename))))
public static void main(String[] args) {
{ System.out.println("byte: " + in.readByte());
String filename = "datafile.dat"; System.out.println("short: " + in.readShort());
String message = "Hi,CodeQuotient!"; System.out.println("int: " + in.readInt());
System.out.println("float: " + in.readFloat());
// Write primitives to an output file System.out.println("double: " + in.readDouble());
try (DataOutputStream out = new DataOutputStream( new System.out.println("boolean: " + in.readBoolean());
BufferedOutputStream( new FileOutputStream(filename)))) System.out.println("boolean: " + in.readBoolean());
{
out.writeByte(107); System.out.print("char: ");
out.writeShort(0xFFF0); // -1 for (int i = 0; i < message.length(); ++i) {
out.writeInt(0x10B7); System.out.print(in.readChar());
out.writeFloat(55.87f); // Can also be done by System.out.print((char)in.readByte());
out.writeDouble(55.56); }
out.writeBoolean(true); System.out.println();
out.writeBoolean(false); } catch (IOException ex) {
for (int i = 0; i < message.length(); ++i) ex.printStackTrace();
out.writeChar(message.charAt(i)); }
out.writeChars(message); }
out.writeBytes(message); }
out.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
Input Output in Java : Buffered Read
Write
• Input-Output using bytes
• Streams which read/write bytes are called Byte streams and streams which
read/write characters are called Char streams.
• To read/write bytes we use InputStream and OutputStream base classes and
further sub-classes for the same: Various sub-classes under InputStream are
FileInputStream, FilterInputStream, ByteArrayInputStream etc. and similary
counterparts under OutputStream class e.g. FileOutputStream, FilterOutputStream
etc.
• Out of these, we generally use BufferedInputStream and BufferedOutputStream
(further sub-classes of FilterInputStream and FilterOutputStream) to read and
write data from devices like keyboard, monitor, hard disk etc.
Reading from an InputStream

• The abstract superclass InputStream declares an abstract method


read() to read one data-byte from the input source:
public abstract int read() throws IOException
The read() method:
• returns the input byte read as an int in the range of 0 to 255, or
• returns -1 if "end of stream" condition is detected, or
• throws an IOException if it encounters an I/O error.
Writing to an OutputStream

• Similar to the input counterpart, the abstract superclass


OutputStream declares an abstract method write() to write a data-
byte to the output sink. write() takes an int. It throws an IOException
if I/O error occurs (e.g., output stream has been closed).

• public void abstract void write(int unsignedByte) throws IOException


Opening & Closing I/O Streams

• You open an I/O stream by constructing an instance of the stream.


Both the InputStream and the OutputStream provides a close()
method to close the stream, which performs the necessary clean-up
operations to free up the system resources.

• public void close() throws IOException // close this Stream


JDK 1.7 introduces a new try-with-resources syntax, which
automatically closes all the opened resources after try or catch, as
follows. This produces much neater codes.

try (FileInputStream in = new FileInputStream(...)) {


......
......
} catch (IOException ex) {
ex.printStackTrace();
} // Automatically closes all opened resource in try (...).
Flushing the OutputStream

• In addition, the OutputStream provides a flush() method to flush the


remaining bytes from the output buffer.

• public void flush() throws IOException // Flush the output


Implementations of
InputStream/OutputStream
• InputStream and OutputStream are abstract classes that cannot be
instantiated.
• You need to choose an appropriate concrete subclass to establish a
connection to a physical device.
• For example, you can instantiate a FileInputStream or
FileOutputStream to establish a stream to a physical disk file.
Buffered I/O Byte-Streams -
• The read()/write() method in InputStream/OutputStream are
designed to read/write a single byte of data on each call. This is
grossly inefficient
• Buffering, which reads/writes a block of bytes from the external
device into/from a memory buffer in a single I/O operation, is
commonly applied to speed up the I/O.
• FileInputStream/FileOutputStream is not buffered. It is often chained
to a BufferedInputStream or BufferedOutputStream, which provides
the buffering
• To chain the streams together, simply pass an instance of one stream
into the constructor of another stream. For example, the following
codes chain a FileInputStream to a BufferedInputStream, and finally, a
DataInputStream:
FileInputStream fileIn = new FileInputStream("in.dat");
BufferedInputStream bufferIn = new BufferedInputStream(fileIn);
DataInputStream dataIn = new DataInputStream(bufferIn);

// or we can do it in a single line as below

DataInputStream in = new DataInputStream( new


BufferedInputStream( new FileInputStream("in.dat")));

You might also like