UNIT V
Overview of Java I/O (Input/Output)
Java I/O (in [Link] package) provides a framework for reading and writing data (input/output)
— to files, memory, network connections, etc.
It uses streams to handle data flow between sources and destinations.
Directories (Using [Link] )
The File class can represent both files and directories.
You can use it to create, delete, list, and check properties of directories.
Example 1: Creating a Directory
import [Link];
public class CreateDirectoryExample {
public static void main(String[] args) {
File dir = new File("exampleDir");
if (![Link]()) {
boolean created = [Link](); // creates one directory
[Link]("Directory created: " + created);
} else {
[Link]("Directory already exists!");
}
}
}
Note: Use mkdir() for a single directory.
Stream in Java
A Stream in Java represents a flow of data between a source and a destination.
It is used for input (reading) and output (writing) operations — such as files, memory, or
network data.
Input Stream: reads data into the program.
Output Stream: writes data out from the program.
Types of Streams
Type Base Class Data Type Used For
Byte Streams InputStream, OutputStream Binary data (8-bit) Images, audio,
video
Character Reader, Writer Text data (16-bit Text files
Streams Unicode)
Object Streams ObjectInputStream, Objects Serialization
ObjectOutputStream
Byte Stream (Copies data from one file to other using bytes)
Byte streams are used to perform input and output of 8-bit binary data. They are suitable for
handling raw data such as images, audio, and video files. The main abstract classes for byte
streams are InputStream and OutputStream.
InputStream
InputStream is
an abstract class that represents the superclass of all classes used to read bytes
from a source. It provides methods like read() and close() to read data from files or other input
devices.
OutputStream
OutputStream is an abstract class that is the superclass of all classes used to write bytes to a
destination. It provides methods like write() and close() to send data to files, memory, or output
devices.
FileInputStream
FileInputStream is
a subclass of InputStream used for reading data from files in the form of bytes.
It is mainly used for reading binary files such as images, audio, or text in byte form.
FileOutputStream
FileOutputStream is
a subclass of OutputStream used for writing data to files in the form of bytes.
It is commonly used for creating or modifying binary and text files.
import [Link].*;
public class ByteStreamExample {
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("[Link]");
FileOutputStream out = new FileOutputStream("output_byte.txt");
int data;
while ((data = [Link]()) != -1) {
[Link](data);
}
[Link]();
[Link]();
[Link]("Byte Stream: File copied successfully!");
}
}
Character Stream (Reads and writes text character by character)
Character streams are used to handle 16-bit Unicode text data. They automatically translate
bytes to characters and vice versa. The main abstract classes for character streams are Reader
and Writer.
import [Link].*;
public class CharStreamExample {
public static void main(String[] args) throws IOException {
FileReader reader = new FileReader("[Link]");
FileWriter writer = new FileWriter("output_char.txt");
int ch;
while ((ch = [Link]()) != -1) {
[Link](ch);
}
[Link]();
[Link]();
[Link]("Character Stream: File copied successfully!");
}
}
BufferedReader and BufferedWriter (Uses buffer to read and write text
efficiently)
BufferedReader
BufferedReaderis a character input stream that reads text efficiently by buffering characters,
allowing faster reading of lines or text blocks. It provides the method readLine() to read text
line by line.
BufferedWriter
is a character output stream that writes text efficiently using a buffer. It reduces
BufferedWriter
the number of disk write operations and provides the newLine() method to write a new line
easily.
import [Link].*;
public class BufferedExample {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output_buffered.txt"));
String line;
while ((line = [Link]()) != null) {
[Link]([Link]());
[Link]();
}
[Link]();
[Link]();
[Link]("Buffered Reader/Writer: File processed!");
}
}
PrintStream (Writes formatted output to a file)
PrintStream is
a subclass of OutputStream that allows printing formatted data to files or consoles.
It provides convenient methods like print(), println(), and printf() for easy output. [Link] is an
instance of PrintStream.
import [Link].*;
public class PrintStreamExample {
public static void main(String[] args) throws IOException {
PrintStream ps = new PrintStream("[Link]");
[Link]("Hello from PrintStream!");
[Link]("Sum of %d + %d = %d", 10, 20, (10 + 20));
[Link]();
[Link]("PrintStream: Output written!");
}
}
RandomAccessFile (Reads and writes at any position in a file)
RandomAccessFileis used to read and write data to a file at any position, allowing both
sequential and non-sequential access. It supports both read ("r") and read/write ("rw") modes.
import [Link].*;
public class RandomAccessExample {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile("[Link]", "rw");
[Link]("Hello Java I/O!");
[Link](0); // Move to start
[Link]("Read from file: " + [Link]());
[Link]();
}
}
Serialization (Saves and restores an object from a file)
Serialization is the process of converting an object into a byte stream so that it can be saved
to a file or sent over a network. The reverse process, called deserialization, restores the object
from the byte stream. It uses ObjectOutputStream and ObjectInputStream classes, and the object’s
class must implement the Serializable interface.
import [Link].*;
// Serializable class
class Student implements Serializable {
String name;
int age;
Student(String n, int a) { name = n; age = a; }
}
public class SerializationExample {
public static void main(String[] args) throws Exception {
Student s1 = new Student("Alice", 20);
public static void main(String[] args) throws Exception {
Student s1 = new Student("Alice", 20);
// Serialize object
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("[Link]"));
[Link](s1);
[Link]();
// Deserialize object
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("[Link]"));
Student s2 = (Student) [Link]();
[Link]();
[Link]("Deserialized Student: " + [Link] + " (" + [Link] + ")");
}
}