Module 9: File Handling and Streams
1. Introduction
File handling allows Java programs to store data permanently by reading from and writing to files. Streams are used to perform input and output operations in Java.
2. What is a Stream?
A stream is a sequence of data. In Java:
- Input Stream – Reads data from a source (e.g., file, keyboard).
- Output Stream – Writes data to a destination (e.g., file, console).
3. File Classes in Java
Java provides classes in the java.io and java.nio.file packages to handle files:
File– Represents a file or directory path.FileReaderandFileWriter– For reading and writing text files.BufferedReaderandBufferedWriter– For efficient reading and writing.FileInputStreamandFileOutputStream– For reading and writing bytes.
4. Creating and Checking Files
import java.io.File;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
try {
File file = new File("example.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
5. Writing to a File
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, this is a test file.\nWelcome to Java file handling!");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
6. Reading from a File
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileExample {
public static void main(String[] args) {
try {
File file = new File("example.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
}
}
7. Using BufferedReader and BufferedWriter
import java.io.*;
public class BufferedExample {
public static void main(String[] args) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("buffered.txt"));
bw.write("Buffered writing is efficient!");
bw.newLine();
bw.write("It reduces the number of I/O operations.");
bw.close();
BufferedReader br = new BufferedReader(new FileReader("buffered.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
8. Byte Streams
Byte streams handle binary data such as images or audio files. Use FileInputStream and FileOutputStream.
import java.io.*;
public class ByteStreamExample {
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("input.jpg");
FileOutputStream output = new FileOutputStream("output.jpg");
int data;
while ((data = input.read()) != -1) {
output.write(data);
}
input.close();
output.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
9. Serialization and Deserialization
Serialization is the process of converting an object into a byte stream to store or transmit it. Deserialization converts it back into an object.
import java.io.*;
class Student implements Serializable {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializationExample {
public static void main(String[] args) {
Student s1 = new Student("Alice", 21);
try {
FileOutputStream fileOut = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(s1);
out.close();
fileOut.close();
System.out.println("Object serialized!");
FileInputStream fileIn = new FileInputStream("student.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Student s2 = (Student) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Student: " + s2.name + ", " + s2.age);
} catch (Exception e) {
e.printStackTrace();
}
}
}
10. Working with NIO Files
The java.nio.file package provides modern, simpler APIs for file manipulation.
import java.nio.file.*;
import java.io.IOException;
public class NIOExample {
public static void main(String[] args) {
try {
Path path = Paths.get("niofile.txt");
Files.write(path, "Hello NIO!".getBytes());
String content = Files.readString(path);
System.out.println("File Content: " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
11. Summary
- Use
FileReader/FileWriterfor text data. - Use
FileInputStream/FileOutputStreamfor binary data. - Use buffering (
BufferedReader,BufferedWriter) for efficiency. - Serialization allows saving entire objects.
- NIO provides simplified and modern file handling tools.
🧠 Practice Exercises
- Create a file and write your name and age into it, then read it back and display the content.
- Copy a text file to another file using
FileInputStreamandFileOutputStream. - Write a program that counts the number of lines in a text file.
- Serialize and deserialize a custom
Bookobject. - Use the
Filesclass to create, write, and read a file in one go.