Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to read txt files in java SE
Jakman (452)

When using java you may want to read text files. Java is a slow language but very powerful.
Here is how

import java.io.File;  // Import the File class
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class Main {
  public static void main(String[] args) {
    try {
      File myObj = new File("example.txt");
      Scanner myReader = new Scanner(myObj);
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");

What this does is it reads a text file. Let me explain the whole script.
Import the Scanner to read Files and the File class to talk to files in the first place. Make an object of the File from the File name and the File class. Then make a scanner object for the previous object. This allows you to read,close and check for the next line in a text file.
Then you make a while statment to see if a nextline is in the file. If so then it would read the next line and print that line out. This would occur until there is no next line in the text file. When that occurs, the file is closed and the program ends. Ask me for any questions or concerns.

davidwbandel (4)

Doesn't work at all.

I've been trying to read in a simple text file (which exists right in my repl.it project) and I get a filenotfoundexception error.

SixBeeps (5349)

This is good to know.
Protip though: you can just do import java.io.* to import everything from java.io so that you can shorten those two imports into one.

Jakman (452)

@SixBeeps thanks for the info on import java.io.* .