Reading and Writing to Files
Text File Reading
Using FileReader and BufferedReader
// Basic file reading
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Using Scanner
try (Scanner scanner = new Scanner(new File("data.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Using Files.readAllLines() (Java 7+)
try {
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Text File Writing
Using FileWriter and BufferedWriter
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("Hello, World!");
writer.newLine();
writer.write("Second line");
} catch (IOException e) {
e.printStackTrace();
}
Appending to File
// true parameter enables append mode
try (BufferedWriter writer = new BufferedWriter(
new FileWriter("output.txt", true))) {
writer.write("Appended text");
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}
Using PrintWriter
try (PrintWriter writer = new PrintWriter(new FileWriter("output.txt"))) {
writer.println("Line 1");
writer.println("Line 2");
writer.printf("Number: %d%n", 42);
} catch (IOException e) {
e.printStackTrace();
}
Binary File Operations
Reading Binary Files
try (FileInputStream fis = new FileInputStream("data.bin");
DataInputStream dis = new DataInputStream(fis)) {
int number = dis.readInt();
double value = dis.readDouble();
String text = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
Writing Binary Files
try (FileOutputStream fos = new FileOutputStream("data.bin");
DataOutputStream dos = new DataOutputStream(fos)) {
dos.writeInt(42);
dos.writeDouble(3.14);
dos.writeUTF("Hello");
} catch (IOException e) {
e.printStackTrace();
}
Object Serialization
Writing Objects
class Student implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int rollNo;
}
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("student.dat"))) {
Student s = new Student();
s.name = "John";
s.rollNo = 101;
oos.writeObject(s);
} catch (IOException e) {
e.printStackTrace();
}
Reading Objects
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("student.dat"))) {
Student s = (Student) ois.readObject();
System.out.println(s.name + " - " + s.rollNo);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
Modern File Operations (Java 7+ NIO.2)
Reading Entire File
// Read all bytes
byte[] bytes = Files.readAllBytes(Paths.get("file.txt"));
String content = new String(bytes, StandardCharsets.UTF_8);
// Read all lines
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
Writing to File
// Write string
String content = "Hello World";
Files.writeString(Paths.get("output.txt"), content);
// Write lines
List<String> lines = Arrays.asList("Line 1", "Line 2", "Line 3");
Files.write(Paths.get("output.txt"), lines);
Copying and Moving Files
// Copy file
Files.copy(Paths.get("source.txt"),
Paths.get("destination.txt"),
StandardCopyOption.REPLACE_EXISTING);
// Move file
Files.move(Paths.get("old.txt"),
Paths.get("new.txt"),
StandardCopyOption.REPLACE_EXISTING);
Deleting Files
try {
Files.delete(Paths.get("file.txt"));
// or use deleteIfExists to avoid exception
Files.deleteIfExists(Paths.get("file.txt"));
} catch (IOException e) {
e.printStackTrace();
}
Checking File Properties
Path path = Paths.get("file.txt");
// Check existence
boolean exists = Files.exists(path);
boolean notExists = Files.notExists(path);
// Check type
boolean isRegularFile = Files.isRegularFile(path);
boolean isDirectory = Files.isDirectory(path);
// Check permissions
boolean isReadable = Files.isReadable(path);
boolean isWritable = Files.isWritable(path);
boolean isExecutable = Files.isExecutable(path);
// Get size
long size = Files.size(path);
// Get last modified time
FileTime lastModified = Files.getLastModifiedTime(path);
Random Access File
Reading at Specific Position
try (RandomAccessFile raf = new RandomAccessFile("data.dat", "r")) {
// Move to position 100
raf.seek(100);
// Read from that position
int value = raf.readInt();
String text = raf.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
Writing at Specific Position
try (RandomAccessFile raf = new RandomAccessFile("data.dat", "rw")) {
// Move to end
raf.seek(raf.length());
// Write data
raf.writeInt(42);
raf.writeUTF("Appended");
} catch (IOException e) {
e.printStackTrace();
}
Quick Reference
| Operation | Class/Method | Purpose |
|---|
| Read text line by line | BufferedReader | Efficient text reading |
| Write text line by line | BufferedWriter | Efficient text writing |
| Read with formatting | Scanner | Parse formatted input |
| Write with formatting | PrintWriter | Formatted output |
| Read binary | DataInputStream | Read primitive types |
| Write binary | DataOutputStream | Write primitive types |
| Read objects | ObjectInputStream | Deserialize objects |
| Write objects | ObjectOutputStream | Serialize objects |
| Modern file ops | Files class | Java 7+ NIO.2 operations |
| Random access | RandomAccessFile | Read/write at any position |
Best Practices
- Always Use try-with-resources: Ensures automatic resource closing
- Handle Exceptions: Always catch IOException and handle appropriately
- Use Buffered Streams: For better performance with large files
- Choose Right Encoding: Specify StandardCharsets.UTF_8 for text files
- Check File Existence: Before reading/writing to avoid exceptions
- Use NIO.2 for Modern Code: Files class provides cleaner API
Common Pitfalls
- Not closing streams (use try-with-resources)
- Platform-dependent line separators (use
System.lineSeparator() or newLine())
- Reading large files entirely into memory
- Not handling checked exceptions
- Mixing character and byte streams incorrectly
Exam Tips
- Remember: BufferedReader/Writer for text, DataInputStream/OutputStream for binary
- Know: try-with-resources syntax and when to use it
- Understand: Difference between FileReader and Files.readAllLines()
- Practice: Writing complete file I/O code with exception handling
- Memorize: Serializable interface requirement for object persistence