2013-06-12 1 views
-1

아래의 파일 .txt에서 데이터를 읽는 방법을 모르겠습니다.fileReader 및 scanner

static final String DATA_PATH = "DataFile.txt"; 

public static void main(String[] args) { 

    Scanner fileReader = null; 
    try { 

     fileReader = new Scanner(new File(DATA_PATH)); 
     //Print out a trace of the program as it is running 
     System.out.println("Debug: Scanner is open "+fileReader); 
    } catch (FileNotFoundException e) { 
     // If the file is not there, an exception will be thrown and the program flow 
     // will directed here. An error message is displayed and the program stops. 
     System.out.println("The file "+DATA_PATH+" was not found!"); 
     System.out.println("The program terminates now."); 
     System.exit(0); 
    } 
+0

정말요? 당신은 심지어 운동 번호를 유지했습니다. – meda

+1

모험심은 어디에 있습니까? :)'Scanner' 클래스 (web || 텍스트 북)에 대한 문서를 살펴보면, 마지막에'fileReader. '와 같이 마침표가있는 변수를 입력한다고해도 IntelliSense가 열리고 몇 가지 아이디어가 있어야합니다. (나는 단지'stackoverflow를 시작하면서'-1') –

답변

1

다음은 스캐너를 사용한 readFile의 예입니다. 따라서 다음과 같은 중요한 패키지를 가져와야합니다.

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

그런 다음 파일의 name 매개 변수와 함께 파일 객체를 만듭니다. 그런 다음 스캐너 개체가 만들어집니다. 마지막으로 while 루프를 사용하여 한 줄씩 또는 원하는대로 읽을 수 있습니다.

public class ScannerReadFile { 
    public static void main(String[] args) { 
     // 
     // Create an instance of File for data.txt file. 
     // 
     File file = new File("data.txt"); 

     try { 
      // 
      // Create a new Scanner object which will read the data 
      // from the file passed in. To check if there are more 
      // line to read from it we check by calling the 
      // scanner.hasNextLine() method. We then read line one 
      // by one till all line is read. 
      // 
      Scanner scanner = new Scanner(file); 
      while (scanner.hasNextLine()) { 
       String line = scanner.nextLine(); 
       System.out.println(line); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

    } 

그래서 여기에서 언급 한 코드부터 시작하여 연습 해보십시오. 웹 사이트의 많은 자습서에서.