Java File Handling
File handling in Java refers to reading data from files and writing data to files stored on the computer's filesystem. This is essential for programs that need to store information permanently — beyond the lifetime of the running program.
Java provides several classes for file handling, primarily in the java.io and java.nio.file packages.
The File Class
The File class in java.io represents a file or directory path. It does not read or write content — it provides information about the file and allows operations like creation, deletion, and listing.
import java.io.File;
public class FileInfoDemo {
public static void main(String[] args) {
File file = new File("notes.txt");
System.out.println("File name: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("Exists: " + file.exists());
System.out.println("Is file: " + file.isFile());
System.out.println("Is directory: " + file.isDirectory());
}
}Creating a New File
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try {
File file = new File("myfile.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("Error creating file: " + e.getMessage());
}
}
}Writing to a File
Using FileWriter
FileWriter writes character data to a file. Pass true as the second argument to append to an existing file instead of overwriting.
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("myfile.txt");
writer.write("Hello, Java File Handling!\n");
writer.write("This is the second line.\n");
writer.close();
System.out.println("Written to file successfully.");
} catch (IOException e) {
System.out.println("Error writing file: " + e.getMessage());
}
}
}Using BufferedWriter for Efficiency
BufferedWriter wraps around FileWriter and buffers the output for better performance when writing large amounts of data.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriteDemo {
public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("report.txt"))) {
bw.write("Sales Report - 2024");
bw.newLine();
bw.write("Total Revenue: Rs. 50,000");
bw.newLine();
bw.write("Total Expenses: Rs. 20,000");
System.out.println("Report written.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Reading from a File
Using FileReader
FileReader reads character data from a file one character at a time.
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("myfile.txt");
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}Using BufferedReader (Most Common)
BufferedReader reads text line by line, making it much more efficient for reading large files.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReadDemo {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("report.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Output (based on what was written earlier):
Sales Report - 2024
Total Revenue: Rs. 50,000
Total Expenses: Rs. 20,000Using Scanner to Read a File
The Scanner class can also read from a file, offering convenient methods like nextLine(), nextInt(), etc.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerFileDemo {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(new File("myfile.txt"));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}Appending to an Existing File
To add content to an existing file without overwriting, pass true as the second argument to FileWriter.
import java.io.FileWriter;
import java.io.IOException;
public class AppendFile {
public static void main(String[] args) {
try (FileWriter fw = new FileWriter("myfile.txt", true)) {
fw.write("This line is appended.\n");
System.out.println("Content appended.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Deleting a File
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
File file = new File("myfile.txt");
if (file.delete()) {
System.out.println("Deleted: " + file.getName());
} else {
System.out.println("Could not delete the file.");
}
}
}Working with Directories
import java.io.File;
public class DirectoryDemo {
public static void main(String[] args) {
// Create a directory
File dir = new File("myFolder");
if (dir.mkdir()) {
System.out.println("Directory created.");
}
// List files in a directory
File currentDir = new File(".");
String[] files = currentDir.list();
if (files != null) {
for (String f : files) {
System.out.println(f);
}
}
}
}File Handling Classes – Summary Table
| Class | Package | Purpose |
|---|---|---|
| File | java.io | File/directory info, create, delete |
| FileWriter | java.io | Write characters to a file |
| FileReader | java.io | Read characters from a file |
| BufferedWriter | java.io | Efficient writing with buffering |
| BufferedReader | java.io | Efficient line-by-line reading |
| Scanner | java.util | Read formatted data from file |
| PrintWriter | java.io | Print formatted text to a file |
Summary
- The
Fileclass represents a file path — use it to create, check, or delete files. FileWriterandBufferedWriterare used to write data to a file.FileReaderandBufferedReaderare used to read data from a file.BufferedReaderandBufferedWriterare preferred for efficiency with large files.- Always close file resources using
close()or usetry-with-resourcesfor automatic cleanup. - File I/O operations can throw
IOException— always handle them with try-catch.
