Skip to main content
Beginnerhow it works

How do you read from and write to a file in Java? Mention the main classes and how to handle errors.

ReportedSource: GeeksforGeeks interview experience: Wipro Elite

Quick answer

Use java.nio.file.Files (readAllLines, lines, writeString) or buffered Reader/Writer streams inside try-with-resources; character streams for text, byte streams for binary; set UTF-8; handle IOException.

Modern NIO (java.nio.file), simplest for most tasks.

Main.java
Path p = Path.of("data.txt");
List<String> lines = Files.readAllLines(p);           // small files
Files.writeString(p, "hello\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
try (Stream<String> s = Files.lines(p)) {             // large files, lazily
    s.filter(l -> !l.isBlank()).forEach(System.out::println);
}

Classic java.io (buffered streams).

Main.java
try (BufferedReader r = new BufferedReader(new FileReader("in.txt"));
     BufferedWriter w = new BufferedWriter(new FileWriter("out.txt"))) {
    String line;
    while ((line = r.readLine()) != null) {
        w.write(line.toUpperCase());
        w.newLine();
    }
}

Key points.

  • Character streams (Reader/Writer) for text; byte streams (InputStream/OutputStream) for binary data such as images.
  • Buffering avoids one system call per character.
  • Specify the charset (StandardCharsets.UTF_8) to avoid platform-dependent encoding bugs.
  • Use try-with-resources so files always close; handle IOException (file missing, permissions).

Discussion