File I/O in Java allows programs to interact with files stored on the file system—reading, writing, creating, deleting, and checking properties of files or directories.
File Class (java.io.File):
The File class represents the path to a file or directory—not the content. It allows you to:
- Check if a file or directory exists
- Create or delete files/directories
- Rename files
- Get file properties (like size, path, read/write permissions)
Common Methods:

Reading from a File:
Java provides two types of streams for reading:
a.) Byte-Oriented (Binary Files)
- FileInputStream (for raw bytes like images, PDFs, etc.)
b.) Character-Oriented (Text Files)
- FileReader → reads text files as characters
- BufferedReader → wraps FileReader for efficient reading
Example: Reading a Text File Using BufferedReader:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFromFile {
public static void main(String[] args) {
String fileName = "my_document.txt"; // Make sure this file exists
// try-with-resources ensures the stream is closed automatically
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // Print each line of the file
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}Writing to a File:
a. Byte-Oriented:
- FileOutputStream
b. Character-Oriented:
- FileWriter → writes characters
- BufferedWriter or PrintWriter → improves performance, adds methods like println()
Example (Reading from a file using BufferedReader):
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
String fileName = "output.txt";
// try-with-resources ensures the writer is closed automatically
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write("Hello, Java File I/O!");
writer.newLine();
writer.write("This is a second line.");
System.out.println("File written successfully.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
}