2013-06-12 189 views
-1

我不明白如何從下面的.txt文件讀取數據。fileReader和掃描儀

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 || textbook)的文檔,即使最後輸入一段時間,比如'fileReader.',也應該打開IntelliSense並給出一些想法。 (當你剛剛啓動stackoverflow時,我不會'-1') –

回答

1

以下是使用掃描儀的readFile示例。因此,您應該導入三個重要的包:

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

之後,您將創建文件對象以及文件的名稱參數。然後,創建掃描儀對象。最後,你可以使用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(); 
     } 

    } 

所以,你可以嘗試從我在這裏提到的代碼開始,練習更多!從網站上的許多教程。