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();
        System.out.println(data);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

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.

You are viewing a single comment. View All
SixBeeps (5353)

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.* .