Java File Handling - Complete Tutorial
Master Java File I/O: Learn to read, write, create, delete files and directories using File, FileReader, FileWriter, BufferedReader, BufferedWriter, FileInputStream, FileOutputStream classes with practical examples.
1. Introduction to File Handling
File handling lets programs read and write persistent data. Java provides java.io for streams and java.nio.file for modern path-based operations.
- Files survive program termination
- Character streams for text
- Byte streams for binary data
- Always handle IOException
import java.io.File;
public class FileIntro {
public static void main(String[] args) {
File f = new File("data.txt");
System.out.println("Exists: " + f.exists());
}
}
2. The File Class
The File class represents file and directory pathnames. It can check existence, create directories, list contents, and delete files.
- exists(), isFile(), isDirectory()
- getName(), getPath(), length()
- mkdir() and mkdirs() for folders
- delete() removes file or empty dir
import java.io.File;
public class FileOps {
public static void main(String[] args) {
File dir = new File("logs");
if (!dir.exists()) dir.mkdir();
System.out.println(dir.isDirectory());
}
}
3. FileReader and FileWriter
FileReader and FileWriter handle character-based text file I/O. They are convenient for small text files but less efficient than buffered variants.
- Character streams for text
- Extend InputStreamReader/OutputStreamWriter
- Specify encoding carefully in production
- Use try-with-resources
import java.io.*;
public class FileWriteText {
public static void main(String[] args) throws IOException {
try (FileWriter fw = new FileWriter("note.txt")) {
fw.write("Hello File");
}
}
}
4. BufferedReader and BufferedWriter
Buffered streams read and write in chunks, reducing system calls. BufferedReader.readLine() is ideal for line-oriented text files.
- Wrap FileReader/FileWriter
- readLine() returns null at EOF
- newLine() writes platform line separator
- Much faster for large files
import java.io.*;
public class ReadLines {
public static void main(String[] args) throws IOException {
try (BufferedReader br = new BufferedReader(
new FileReader("note.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
5. FileInputStream and FileOutputStream
Byte streams read and write raw bytes for images, audio, and serialized data. They work with binary files where character encoding does not apply.
- Binary file copy
- read() returns -1 at end
- Use byte array buffer in loops
- Pair with BufferedInputStream for speed
import java.io.*;
public class BinaryCopy {
public static void main(String[] args) throws IOException {
try (FileInputStream in = new FileInputStream("a.dat");
FileOutputStream out = new FileOutputStream("b.dat")) {
int b;
while ((b = in.read()) != -1) out.write(b);
}
}
}
6. Built-in File Utilities
Java NIO Files class provides static helpers: copy, move, delete, readAllBytes, and walk for directory trees with less boilerplate.
- Files.readString(Path) — Java 11+
- Files.writeString for quick writes
- Paths.get() builds path objects
- StandardOpenOption for append/create
import java.nio.file.*;
public class NioFiles {
public static void main(String[] args) throws Exception {
Path path = Paths.get("hello.txt");
Files.writeString(path, "NIO write");
String text = Files.readString(path);
System.out.println(text);
}
}
7. Practical File Examples
Common tasks include logging to files, reading configuration, and copying backups. Combine streams with exception handling for robust code.
- Append log entries with BufferedWriter
- Count lines in a text file
- Copy file with Files.copy
- Check file size before processing
import java.io.*;
public class LogAppend {
public static void main(String[] args) throws IOException {
try (BufferedWriter bw = new BufferedWriter(
new FileWriter("app.log", true))) {
bw.write("Server started");
bw.newLine();
}
}
}
8. File Handling Best Practices
Reliable file code closes resources, handles missing files gracefully, and uses appropriate APIs for text vs binary data.
- Always use try-with-resources
- Check exists() before read if needed
- Prefer NIO Files for simple operations
- Specify Charset for text encoding
- Validate paths to prevent directory traversal