Trendingat

02Home & Garden · Updated

How to Read a File in Java: A Practical Guide

Short answer

Use Java’s file-reading APIs to access text or bytes

For a text file, use Files.readString for a small file or a BufferedReader to read line by line. Specify the character encoding, handle possible I/O errors, and close resources with try-with-resources.

Text filesUse UTF-8 unless the file specifies another encodingExplained in: Step-by-Step
Small filesRead them with Files.readStringExplained in: Step-by-Step
Large filesProcess them line by lineExplained in: Step-by-Step
Reading time6 min7 sections, about 1,330 words

What You’ll Need

  • A Java development kit and a Java project or source file.
  • A file you can access, plus its path. A relative path is resolved from the program’s working directory, which may not be the folder containing your Java source code.
  • For text, the file’s character encoding if known. UTF-8 is a good choice when you control how the file is saved.

Step-by-Step

  1. Choose the right approach. For a small text file, Files.readString is concise. For a file you want to process one line at a time, use Files.newBufferedReader. For images, PDFs, or other binary data, read bytes instead of converting the contents to text. Loading an entire large file into a string or byte array can use substantial memory.
  2. Import the required classes. The examples below use java.nio.file.Files, java.nio.file.Path, and java.nio.charset.StandardCharsets. Add these imports at the top of your Java file:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Path;
  3. Set the file path. Create a Path using the file’s location. For a file named notes.txt in the working directory, use:
    Path path = Path.of("notes.txt");

    To avoid confusion, you can use an absolute path, or put the file in the project’s working directory. Paths written as strings should use forward slashes or escaped backslashes; for example, "C:\\data\\notes.txt" in Java source.

  4. Read a small text file. Call Files.readString with the path and an explicit charset:
    try {
        String text = Files.readString(path, StandardCharsets.UTF_8);
        System.out.println(text);
    } catch (IOException e) {
        System.err.println("Could not read file: " + e.getMessage());
    }

    This reads the whole file into memory and returns its contents as one string. The overload with a charset is available in modern Java; if your project targets an older Java release, use a BufferedReader or check the API supported by that release.

  5. Read line by line. Use try-with-resources so Java closes the reader automatically, including when an error occurs:
    try (BufferedReader reader = Files.newBufferedReader(
            path, StandardCharsets.UTF_8)) {
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        System.err.println("Could not read file: " + e.getMessage());
    }

    The loop ends when readLine() returns null. Each returned line excludes its line-ending characters. Process each line inside the loop when possible, rather than collecting every line, to keep memory use predictable.

  6. Read binary data when appropriate. For a file that is not text, use Files.readAllBytes(path) for a small file:
    try {
        byte[] data = Files.readAllBytes(path);
        System.out.println("Bytes read: " + data.length);
    } catch (IOException e) {
        System.err.println("Could not read file: " + e.getMessage());
    }

    Do not decode arbitrary bytes as UTF-8 unless the file is actually text in that encoding. For large binary files, use an input stream and process manageable chunks instead of loading everything at once.

  7. Handle errors deliberately. File operations can throw IOException, for example if the path is missing, access is denied, or a device fails. Catch it where you can respond meaningfully, or declare it with throws IOException and let a calling method handle it. Avoid silently ignoring the exception: the program may otherwise appear to have read an empty file.
  8. Run and verify the result. Run the program from the same environment you will use in practice. Check that the output contains the expected text or byte count. If a relative path fails, print or inspect Path.of("").toAbsolutePath() to see the working directory, then adjust the file location or path.

Common Mistakes

Assuming the path is relative to the source file: It is usually relative to the process’s working directory, which can vary between an IDE, a terminal, and a scheduled task. Verify the working directory or use a well-defined path.

Using the wrong charset: Text decoded with the wrong encoding may show replacement characters or unreadable symbols. Use the encoding used to save the file; specify it explicitly so behavior is predictable.

Forgetting to close a reader: Open files use operating-system resources. Use try-with-resources for readers and streams rather than relying on garbage collection or manual cleanup in only the successful path.

Reading a huge file all at once: readString and readAllBytes keep the whole contents in memory. For large files, read progressively with a buffered reader or input stream.

Treating every file as text: Binary files do not have ordinary lines or necessarily valid characters. Use byte-oriented APIs for binary formats.

Tips

  • Use Path.of to represent paths and avoid manually joining folder names with separators; Java handles the platform’s path conventions.
  • For files bundled with an application, consider loading them as classpath resources rather than relying on the current working directory. A resource inside a JAR is not necessarily an ordinary filesystem file.
  • If you need to check whether a path exists, Files.exists(path) can help with diagnostics, but a check followed by a read is not a guarantee that the read will succeed. Keep handling errors around the actual read.
  • Choose a simple method based on file size and purpose: whole-file methods suit small inputs; streaming methods suit larger inputs or line-by-line processing.

Troubleshooting

“No such file” or “The system cannot find the path specified”: Print the absolute working directory, confirm the filename and extension, and check each folder in the path. Ensure the file is present where the running program expects it.

“Access denied”: Confirm the account running Java has permission to read the file, and check whether another program or system policy is restricting access. Do not assume changing the path alone will fix a permissions problem.

Garbled characters: Confirm the file’s encoding and use the same charset when reading. If it is a binary file, use a byte-reading method rather than a text reader.

The program prints nothing: Check that the file is not empty, that the correct file was opened, and that the output is not being sent to a different console. Print the resolved path and handle exceptions visibly while debugging.

Memory errors or slow processing: Replace whole-file reading with line-by-line or chunk-based processing. Avoid building a second in-memory copy of the entire file if you do not need one.

Frequently Asked Questions

What is the easiest way to read a text file in Java?

For a small file on a modern Java version, use Files.readString(path, StandardCharsets.UTF_8). For larger files, a BufferedReader lets you handle one line at a time.

How do I read a file line by line?

Open a BufferedReader with Files.newBufferedReader, then loop while readLine() is not null. Put the reader in a try-with-resources statement so it closes automatically.

Why does Java say my file does not exist?

The path may be resolved from a different working directory than you expect, or the filename may be misspelled. Print the absolute working directory and verify the file’s actual location.

Should I use FileReader or Files?

For most new code, the Files methods with a Path are convenient and let you specify a charset explicitly. Older FileReader usage can be valid, but be careful to control the encoding.

Can I use these methods for a PDF or image?

Use byte-oriented reading for binary files, not a text reader. Reading raw bytes does not interpret a PDF or image; use a library designed for that file format if you need to inspect its contents.

Further reading: Oracle Java Documentation. Details can change, so check the official page for anything that matters to you. Spotted a mistake? Tell us. How we write an answer.