In Java file handling, the classes you mentioned are part of the java.
io package and
serve different purposes for reading and writing files. Below is an explanation based on
the Oracle Java documentation, including when to use each.
1. BufferedReader (Efficient text file reading)
Oracle Docs: BufferedReader
When to Use:
• When reading text files efficiently.
• When reading large files line-by-line to save memory.
Example:
java
CopyEdit
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
2. BufferedWriter (Efficient text file writing)
Oracle Docs: BufferedWriter
When to Use:
• When writing text to a file efficiently.
• When writing large amounts of text and reducing disk I/O.
Example:
java
CopyEdit
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
writer.write("Hello, Java!");
writer.newLine();
writer.flush();
3. File (Represents file or directory)
Oracle Docs: File
When to Use:
• When checking file existence.
• When creating, deleting, or modifying file properties (not for reading/writing
data).
Example:
java
CopyEdit
File file = new File("example.txt");
if (file.exists()) {
System.out.println("File exists: " + file.getAbsolutePath());
4. FileReader (Basic character stream reading)
Oracle Docs: FileReader
When to Use:
• When reading text files in a simple way (without buffering).
Example:
java
CopyEdit
try (FileReader reader = new FileReader("example.txt")) {
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
Better Alternative: Use BufferedReader for performance.
5. FileWriter (Basic character stream writing)
Oracle Docs: FileWriter
When to Use:
• When writing text files in a simple way.
• When appending text using new FileWriter("example.txt", true).
Example:
java
CopyEdit
try (FileWriter writer = new FileWriter("example.txt")) {
writer.write("Hello, Java!");
Better Alternative: Use BufferedWriter for better performance.
6. FileInputStream (Read binary files)
Oracle Docs: FileInputStream
When to Use:
• When reading binary files (e.g., images, PDFs, audio).
Example:
java
CopyEdit
try (FileInputStream fis = new FileInputStream("image.png")) {
int data;
while ((data = fis.read()) != -1) {
System.out.print(data + " ");
Better Alternative: Use BufferedInputStream for efficiency.
7. FileOutputStream (Write binary files)
Oracle Docs: FileOutputStream
When to Use:
• When writing binary files (e.g., images, PDFs, audio).
Example:
java
CopyEdit
try (FileOutputStream fos = new FileOutputStream("output.png")) {
fos.write(new byte[]{65, 66, 67}); // Writes binary data
Better Alternative: Use BufferedOutputStream for efficiency.
8. ObjectOutputStream (Serialize objects to file)
Oracle Docs: ObjectOutputStream
When to Use:
• When saving Java objects to a file (serialization).
Example:
java
CopyEdit
import java.io.*;
class Person implements Serializable {
String name;
Person(String name) { this.name = name; }
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("object.dat"))) {
oos.writeObject(new Person("Alice"));
}
9. ObjectInputStream (Deserialize objects from file)
Oracle Docs: ObjectInputStream
When to Use:
• When reading Java objects from a file (deserialization).
Example:
java
CopyEdit
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("object.dat"))) {
Person person = (Person) ois.readObject();
System.out.println(person.name);
10. PrintWriter (Easier formatted text writing)
Oracle Docs: PrintWriter
When to Use:
• When writing formatted text to a file (like System.out.println).
Example:
java
CopyEdit
try (PrintWriter writer = new PrintWriter("example.txt")) {
writer.println("Hello, Java!");
writer.printf("Pi: %.2f", Math.PI);
Benefit: Provides println() and printf() for formatted output.
Summary: When to Use What?
Class Use Case
BufferedReader Read text files efficiently.
BufferedWriter Write text files efficiently.
File Check existence, create, delete files.
FileReader Read text files (basic).
FileWriter Write text files (basic).
FileInputStream Read binary files (images, PDFs).
FileOutputStream Write binary files (images, PDFs).
ObjectOutputStream Serialize Java objects to file.
ObjectInputStream Deserialize Java objects from file.
PrintWriter Write formatted text (like printf()).
Class Methods in Java File Handling (java.io package)
Class methods in Java file handling are static methods that belong to utility classes like
Files and Paths (from java.nio.file) and File (from java.io). These methods do not require
object creation and can be used directly.
1⃣ File Class (java.io.File) - Class Methods
The File class has several static methods to handle file operations.
Key Static Methods in File
Method Description
File.createTempFile(String prefix, String
Creates a temporary file.
suffix)
File.createTempFile(String prefix, String
Creates a temp file in a specific directory.
suffix, File directory)
Method Description
Returns the system file separator (/ for
File.separator
Linux/macOS, \ for Windows).
Returns the system file separator as a
File.separatorChar
character.
Returns the system path separator (; for
File.pathSeparator
Windows, : for Linux/macOS).
Returns the system path separator as a
File.pathSeparatorChar
character.
Example: Creating a Temporary File
java
CopyEdit
import java.io.File;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
try {
File tempFile = File.createTempFile("temp", ".txt");
System.out.println("Temporary file created: " + tempFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
Uses createTempFile() to generate a temp file without creating a File object
manually.
2⃣ Files Class (java.nio.file.Files) - Class Methods
The Files class provides many static utility methods for file handling.
Key Static Methods in Files
Method Description
Files.exists(Path path) Checks if a file exists.
Files.notExists(Path path) Checks if a file does not exist.
Files.createFile(Path path) Creates a new file.
Files.createDirectory(Path path) Creates a new directory.
Files.delete(Path path) Deletes a file or directory.
Files.copy(Path source, Path target, CopyOption...
Copies a file.
options)
Files.move(Path source, Path target,
Moves or renames a file.
CopyOption... options)
Reads all lines of a text file into a
Files.readAllLines(Path path)
List<String>.
Files.write(Path path, List<String> lines) Writes a list of strings to a file.
Example: Checking If a File Exists
java
CopyEdit
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
if (Files.exists(path)) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
Uses Files.exists() to check file existence without creating an object.
3⃣ Paths Class (java.nio.file.Paths) - Class Methods
The Paths class provides static methods to create Path objects.
Key Static Methods in Paths
Method Description
Paths.get(String first, String... more) Returns a Path object for a given file path.
Example: Getting a File Path
java
CopyEdit
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathsExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
System.out.println("File Path: " + path.toAbsolutePath());
Uses Paths.get() to create a Path without creating an object.
Summary: Class Methods in Java File Handling
Class Static Methods Purpose
createTempFile(), separator, Create temp files, get system-
File
pathSeparator specific separators.
exists(), createFile(), delete(), copy(),
Files Work with files and directories.
readAllLines()
Paths get() Get Path objects easily.