簡體   English   中英

從文件讀取Java掃描程序

[英]Java Scanner Read from File

讓我首先確定以下事實:我是Java的新手,所以請耐心等待。

在我的編程課上,我們使用Scanner課進行了一項在家練習的練習。 該活動顯示以下代碼以供執行:

import java.io.*;
import java.util.*;

public class FileReadWrite {

     public static void main(String[] args) throws FileNotFoundException {
          String[] strArr = new String[100];

          int size = 0;

          try {
               Scanner scFile = new Scanner(new File("Names1.txt"));
               while (scFile.hasNext()) {
                    strArr[size] = scFile.next();
                    size++;
               }
               scFile.close();

               for (int i = 0; i < size; i++) {
                    System.out.print(strArr[i] + " ");
               }
          } catch (FileNotFoundException e) {
               System.err.println("FileNotFoundException: " + e.getMessage());
          }

     }
}

該程序似乎無法正常工作。 我使用NetBeans來運行代碼,並且在運行代碼時,它不會在文本文件Names.txt中顯示數據。 這是為什么? 該程序確實可以完全構建而沒有錯誤。

我嘗試遍歷Scanner類javadocs,但這對我沒有幫助。

請向我解釋,以便我可以從錯誤中學習。

謝謝,約翰

我在Mac上嘗試了您的代碼,並且可以正常工作。 因此,我認為您可能輸入了Names1.txt文件錯誤的路徑。

在Java中,當您僅使用“ what_ever_file_name.txt”作為文件路徑時,Java只會在源代碼文件夾中搜索文件。 如果未找到任何內容,將拋出“ FILE_NOT_FOUND_EXCEPTION”。

我同意user2170674。 我還使用Eclipse在Windows機器上嘗試了您的代碼,一切順利。 也許您將文件放在錯誤的路徑中。 兩種選擇:

  • 您可以使用完整路徑,例如(如果使用Windows)“ C:\\ Names1.txt”;
  • 或更通用的解決方案,使用JFileChooser:

      // create your FileChooser final JFileChooser chooser = new JFileChooser(); // open the FileChooser int returnValue = chooser.showOpenDialog(null); // if you select a file if (returnValue == JFileChooser.APPROVE_OPTION) { // get the file and do what you need File file = chooser.getSelectedFile(); } else { // throw an exception or just a message in the log... } 

您的代碼看起來不錯。
調試一些消息。
最后,添加System.out.println()System.out.flush()
將異常塊的位置移到文件使用后(盡量減小塊的大小),然后在finally塊內移動close()。
確保查看Netbeans輸出窗口(Window-> Output-> Output)

public class FileReadWrite {

 public static void main(String[] args) throws FileNotFoundException {
      System.out.println("##### Starting main method...");
      String[] strArr = new String[100];

      int size = 0;

      try {
           Scanner scFile = new Scanner(new File("Names1.txt"));
           while (scFile.hasNext()) {
                strArr[size] = scFile.next();
                size++;
           }
           System.out.println("##### Finished scan.  Found %d tokens.", size);
      } catch (FileNotFoundException e) {
           System.err.println("FileNotFoundException: " + e.getMessage());
      } catch (Exception e) {
           System.err.println("Exception: " + e.getMessage());
           e.printStackTrace();
      } finally {
           if (scFile != null) {
               scFile.close();
               System.out.println("##### Closed scanner.");
           }
      }
      System.out.println("##### Printing tokens...");

      for (int i = 0; i < size; i++) {
           System.out.print(strArr[i] + " ");
      }
      System.out.println("");
      System.out.println("##### Exiting main.");
 }
}

這是一個工作示例。 也許嘗試使用BufferedReader。

import java.io.*;
import java.util.Scanner;

public class ScanXan {
public static void main(String[] args) throws IOException {

    Scanner s = null;

    try {
        s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));

        while (s.hasNext()) {
            System.out.println(s.next());
        }
    } finally {
        if (s != null) {
            s.close();
        }
    }
}
}

來自http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM