Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Is there a java tutorial on how to open a text file and read its content?

I browsed the Java track but didn't find anything labeled files, reading a text doc, taking in a file, etc.

1 Answer

Here's a basic example for reading a text file:

public static void main(String... args) {
    // Specify the encoding of the file.
    Charset encoding = Charset.forName("UTF-8");
    // Path to the file
    Path file = Paths.get("my_file.txt");

    // Try with resources to close reader at the end.
    try(BufferedReader br = Files.newBufferedReader(file, encoding)) {
        // The line read in.
        String line;

        // Combine assignment with null check (null being EOF).
        // Could put the assignment on its on line if you'd prefer.
        while((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } 
    catch (IOException e) {
        e.printStackTrace();
    }
}

Oracle's tutorial will likely have any more information you need.