How to read a file using Java

Configurare noua (How To)

Situatie

In the following example, we use the Scanner class to read the contents of the text file.

Solutie

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {  
  public static void main(String[] args) {  
    try {
      File myObj = new File("test.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();
    } 
  }  
}

Tip solutie

Permanent

Voteaza

(2 din 9 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?