File I/O in Java

    Atul Kabra3 min readUpdated

    File I/O (input/output) is how a Java program reads data from files and writes results back to disk. Modern Java centres on two types in java.nio.file: Path (a location in the file system) and the Files utility class (static methods to read, write, copy, and inspect). For small files you can read or write everything in one call; for large files you stream line by line. Because disk operations can fail, file methods throw the checked IOException, so you handle it with try-catch or declare it.

    Building a Path

    import java.nio.file.Path;
    
    Path file = Path.of("notes.txt");                 // relative to the working directory
    Path nested = Path.of("data", "students.csv");    // joins segments safely
    

    Path.of is the modern way to name a file; it avoids fragile string concatenation of slashes.

    Writing a file

    For small content, Files.writeString writes the whole text in one call (and creates the file if needed).

    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.io.IOException;
    
    Path file = Path.of("greeting.txt");
    try {
        Files.writeString(file, "Namaste from Jalgaon!\nSecond line.\n");
        System.out.println("File written.");
    } catch (IOException e) {
        System.out.println("Could not write: " + e.getMessage());
    }
    

    To append instead of overwrite, pass StandardOpenOption.APPEND.

    Reading a whole small file

    Path file = Path.of("greeting.txt");
    try {
        String content = Files.readString(file);   // entire file into a String
        System.out.println(content);
    
        // Or read as a list of lines:
        var lines = Files.readAllLines(file);
        System.out.println("Line count: " + lines.size());
    } catch (IOException e) {
        System.out.println("Could not read: " + e.getMessage());
    }
    

    readString and readAllLines are convenient — but they load the whole file into memory, so reserve them for small files.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses

    Streaming a large file line by line

    For big files, stream so you never hold the whole thing in memory at once. try-with-resources closes the stream automatically.

    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.io.IOException;
    import java.util.stream.Stream;
    
    Path big = Path.of("large-log.txt");
    try (Stream<String> lines = Files.lines(big)) { // lazy, closed at end of try
        lines.filter(line -> line.contains("ERROR"))
             .forEach(System.out::println);
    } catch (IOException e) {
        System.out.println("Read failed: " + e.getMessage());
    }
    

    Files.lines returns a lazy Stream you must close — hence the try-with-resources.

    Useful Files checks

    Path file = Path.of("greeting.txt");
    System.out.println(Files.exists(file));      // true / false
    System.out.println(Files.isReadable(file));  // can we read it?
    // Files.delete(file);                        // remove it (throws if missing)
    // Files.copy(src, dest);                     // copy a file
    

    Common mistakes

    • Reading huge files with readAllLines/readString. This can exhaust memory. Stream with Files.lines for large files.
    • Not closing streams. Files.lines and reader/writer streams must be closed; use try-with-resources.
    • Ignoring IOException. File operations can fail (missing file, no permission). Handle or declare the checked exception.
    • Assuming the working directory. Relative paths resolve against wherever the program runs from. Print Path.of("x").toAbsolutePath() if unsure.
    • Overwriting when you meant to append. Files.writeString replaces by default; pass StandardOpenOption.APPEND to add to the end.

    FAQ

    Why java.nio.file instead of the old java.io.File? The newer Path/Files API is clearer, has better error reporting, and offers convenient one-line helpers. Prefer it for new code.

    How do I write CSV? Build each line as text (values joined by commas) and write the lines; for complex CSV with quoting, a small library helps, but the file mechanics are the same.

    Keep going

    Next, cement the basics with 15 Java Programs for Beginners, or revisit JDBC. All tutorials are on the Java hub; for guided practice in Jalgaon, see the Java course.


    Practise real file-handling tasks at Infoplanet, Jalgaon. Join the waitlist for the Java course.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses
    Atul Kabra

    Founder, Infoplanet

    Atul Kabra founded Infoplanet in 2001 and has spent over two decades teaching programming — C, C++, Java, databases and more — to students across Maharashtra.

    Related guides