Chapter 12
File Handling in Java
1. Basics of Input and Output Streams
What are Streams?
Streams in Java are used to read from and write to data sources (e.g., files, memory, console, etc.).
Java supports two major types of streams:
• InputStream / Reader → to read data
• OutputStream / Writer → to write data
2. Types of Streams in Java
Stream Type Class Data Type
Byte Stream (Input) FileInputStream Binary
Byte Stream (Output) FileOutputStream Binary
Char Stream (Input) FileReader Text (char)
Char Stream (Output) FileWriter Text (char)
Buffered Streams BufferedReader, BufferedWriter Text with line operations
Object Streams ObjectInputStream, ObjectOutputStream Objects (serialization)
3. Byte Stream Example
import java.io.*;
public class ByteStreamDemo {
public static void main(String[] args) throws IOException {
String content = "Java File Handling Byte Stream Example.";
// Writing to a file
FileOutputStream fos = new FileOutputStream("byte_file.txt");
fos.write(content.getBytes());
fos.close();
// Reading character by character
FileInputStream fis = new FileInputStream("byte_file.txt");
int ch;
System.out.println("Reading by character:");
while ((ch = fis.read()) != -1) {
System.out.print((char) ch);
}
fis.close();
}
}
content.getBytes() ?
In Java, the method getBytes() is used to convert a String into a byte array (byte[]). This is essential
when working with byte streams (like FileOutputStream), which handle raw binary data—not
character data.
Why Use getBytes()?
• Byte streams such as FileOutputStream expect data in bytes (byte[]), not characters or strings.
• getBytes() allows you to write textual data using byte-oriented streams.
import java.io.*;
class Create3
{ public static void main(String args[]) throws IOException
{ String str = "This is an Institute" + "\n You are a student"; // take a String
//Connect a file to FileWriter
FileWriter fw = new FileWriter ("textfile");
//read chars from str and send to fw
for (int i = 0; i<str.length() ; i++)
fw.write (str.charAt (i) );
fw.close ();
}
}
4. Character Stream Example
import java.io.*;
public class CharStreamDemo {
public static void main(String[] args) throws IOException {
String content = "Java supports Character Streams.";
// Writing
FileWriter fw = new FileWriter("char_file.txt");
fw.write(content);
fw.close();
// Reading character by character
FileReader fr = new FileReader("char_file.txt");
int c;
System.out.println("\nReading by character:");
while ((c = fr.read()) != -1) {
System.out.print((char) c);
}
fr.close();
}
}
5. Buffered Streams (Line & Word Reading)
import java.io.*;
public class BufferedStreamDemo {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("buffered.txt"));
bw.write("Java is powerful.\nFile handling is essential.\nStreams are useful.");
bw.close();
BufferedReader br = new BufferedReader(new FileReader("buffered.txt"));
String line;
System.out.println("\nReading line by line:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
6. Console Input/Output Example
import java.io.*;
public class ConsoleIODemo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = br.readLine();
System.out.println("Hello, " + name + "!");
}
}
7. Object Serialization & Deserialization
import java.io.*;
class Student implements Serializable {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class ObjectStreamDemo {
public static void main(String[] args) throws Exception {
// Serialization
Student s = new Student(1, "Mahesh");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"));
oos.writeObject(s);
oos.close();
// Deserialization
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"));
Student s2 = (Student) ois.readObject();
ois.close();
System.out.println("ID: " + s2.id + ", Name: " + s2.name);
}
}
Why do we implement Serializable in the Student class?
What is Serializable?
Serializable is a marker interface in Java (java.io.Serializable). It enables an object to be converted
into a byte stream—which is required for writing the object to a file or sending it over a network.
Why it's required:
Java's ObjectOutputStream can only write objects to a file if the object's class implements Serializable.
If a class does not implement it and you try to serialize its object, you'll get a NotSerializableException.
How the Layers Work:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"));
oos.writeObject(s);
[Student Object]
| --- writeObject()
[ObjectOutputStream] → [FileOutputStream] → [File]
[File] → [FileInputStream] → [ObjectInputStream] → readObject() → [Student Object]
Summary Chart
Topic Input Class Output Class Method Used
Byte Stream FileInputStream FileOutputStream read(), write()
Character Stream FileReader FileWriter read(), write()
Buffered Stream BufferedReader BufferedWriter readLine(), write()
Console I/O BufferedReader PrintWriter readLine(), println()
Object Stream ObjectInputStream ObjectOutputStream readObject(), writeObject()
Examples
Java Program to Copy File Content
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
// Source and destination file paths
String sourceFile = "source.txt";
String destFile = "destination.txt";
try {
// Create reader and writer
FileReader reader = new FileReader(sourceFile);
FileWriter writer = new FileWriter(destFile);
int ch;
while ((ch = reader.read()) != -1) {
writer.write(ch); // write character by character
}
// Close both files
reader.close();
writer.close();
System.out.println("File copied successfully from " + sourceFile + " to " + destFile);
} catch (IOException e) {
System.out.println("An error occurred during file copying.");
e.printStackTrace();
}
}
}
Java Program: Count and Save Palindrome Words
1. Reads content from a text file
2. Identifies and counts all palindrome words
3. Writes all palindrome words to another file
import java.io.*;
import java.util.*;
public class PalindromeWordProcessor {
public static void main(String[] args) {
String inputFile = "input.txt"; // File to read
String outputFile = "palindromes.txt"; // File to write palindromes
int palindromeCount = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
String line;
while ((line = br.readLine()) != null) {
String[] words = line.split("\\s+"); // split by whitespace
for (String word : words) {
word = word.replaceAll("[^a-zA-Z]", "").toLowerCase(); // clean punctuation
if (!word.isEmpty() && isPalindrome(word)) {
bw.write(word);
bw.newLine();
palindromeCount++;
}
}
}
br.close();
bw.close();
System.out.println("Total palindrome words found: " + palindromeCount);
System.out.println("Palindrome words written to: " + outputFile);
} catch (IOException e) {
System.out.println("Error processing files.");
e.printStackTrace();
}
}
// Function to check if a word is a palindrome
public static boolean isPalindrome(String word) {
int i = 0, j = word.length() - 1;
while (i < j) {
if (word.charAt(i) != word.charAt(j)) return false;
i++;
j--;
}
return true;
}
}