codegurukool.com · Free coding tutorials & online compiler

Home › Java Tutorial › Java file handling

Java file handling

Read and write files.

Modern Java reads and writes files with java.nio.file.Files, for example Files.writeString, Files.readAllLines and Files.delete. A BufferedReader reads line by line, and try-with-resources closes it automatically. The example reads from a String so it runs anywhere.

Example code

import java.io.*;

public class Main {
  public static void main(String[] args) throws IOException {
    // Real file: new BufferedReader(new FileReader("data.txt"))
    try (BufferedReader br = new BufferedReader(new StringReader("line one\nline two"))) {
      String line;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }
    }
  }
}

Run this code in the online editor

← Java user inputJava packages, imports and dates →