← Java EnglishChapter 12 of 13

File I/O

## Learning Objectives - Read and write text files - Work with binary files - Use try-with-resources - Handle I/O exceptions ## File Reading ### Scanner (Simple) ```java import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; try (Scanner scanner = new Scanner(new File("input.txt"))) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } } catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); } ``` ### BufferedReader (Efficient) ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; 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(); } ``` ## File Writing ### FileWriter (Simple) ```java import java.io.FileWriter; import java.io.IOException; try (FileWriter writer = new FileWriter("output.txt")) { writer.write("Hello, World!\n"); writer.write("Second line"); } catch (IOException e) { e.printStackTrace(); } ``` ### BufferedWriter (Efficient) ```java import java.io.BufferedWriter; import java.io.FileWriter; try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) { writer.write("Hello"); writer.newLine(); writer.write("World"); } catch (IOException e) { e.printStackTrace(); } ``` ## Buffered Streams ### Why Buffered? | Class | Use Case | |-------|----------| | BufferedReader | Read text efficiently | | BufferedWriter | Write text efficiently | | BufferedInputStream | Read binary efficiently | | BufferedOutputStream | Write binary efficiently | ## Binary Files ### DataInputStream / DataOutputStream ```java // Writing try (DataOutputStream out = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("data.bin")))) { out.writeInt(42); out.writeDouble(3.14); out.writeUTF("Hello"); } catch (IOException e) { e.printStackTrace(); } // Reading try (DataInputStream in = new DataInputStream( new BufferedInputStream(new FileInputStream("data.bin")))) { int num = in.readInt(); double d = in.readDouble(); String s = in.readUTF(); } catch (IOException e) { e.printStackTrace(); } ``` ## Object Serialization ### Serialize Objects ```java import java.io.Serializable; public class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } } ``` ### Write/Read Objects ```java import java.io.*; try (ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("person.bin"))) { Person p = new Person("Alice", 25); out.writeObject(p); } catch (IOException e) { e.printStackTrace(); } try (ObjectInputStream in = new ObjectInputStream( new FileInputStream("person.bin"))) { Person p = (Person) in.readObject(); System.out.println(p.name + " - " + p.age); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } ``` ## File Class ### File Operations ```java import java.io.File; File file = new File("example.txt"); // Check properties file.exists(); file.isFile(); file.isDirectory(); file.length(); // File size in bytes file.lastModified(); // Timestamp // Create/Delete file.createNewFile(); file.mkdir(); // Create directory file.mkdirs(); // Create directory + parents file.delete(); // Rename file.renameTo(new File("new_name.txt")); ``` ### List Directory ```java File dir = new File("myfolder"); if (dir.isDirectory()) { File[] files = dir.listFiles(); for (File f : files) { System.out.println(f.getName() + " - " + (f.isFile() ? "File" : "Dir")); } } ``` ## Path (Java NIO) ### Modern Path Handling ```java import java.nio.file.Path; import java.nio.file.Paths; Path path = Paths.get("folder", "subfolder", "file.txt"); // Operations path.getFileName(); path.getParent(); path.getRoot(); path.toAbsolutePath(); path.normalize(); // Remove redundancies // File operations Files.exists(path); Files.readAllLines(path); Files.write(path, "content".getBytes()); ``` ## Reading All Lines ### Java 11+ One-Liner ```java import java.nio.file.Files; String content = Files.readString(Path.of("file.txt")); List lines = Files.readAllLines(Path.of("file.txt")); ``` ## File Paths ### Separators ```java // Use File.separator or / String path = "folder" + File.separator + "file.txt"; String path2 = "folder/file.txt"; // Or Path Path path3 = Paths.get("folder", "file.txt"); ``` ## Try-with-Resources ### Auto-Close ```java try (Scanner scanner = new Scanner(new File("input.txt")); FileWriter writer = new FileWriter("output.txt")) { // Use scanner and writer } catch (IOException e) { e.printStackTrace(); } ``` ## Common Patterns ### Copy File ```java Files.copy(source, target); Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); ``` ### Read Entire File ```java String content = Files.readString(Path.of("file.txt")); ``` ### Write Entire File ```java Files.writeString(Path.of("file.txt"), "content"); ``` ## Summary - Use Scanner for simple input; BufferedReader for efficient text reading - Use FileWriter for simple output; BufferedWriter for efficient writing - File class for file/directory operations - Path (NIO) for modern file handling - Try-with-resources for automatic cleanup - Serializable for object persistence - Files utility class for common operations

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →