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;  // Import the File class
import;  // 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.

You are viewing a single comment. View All