简体   繁体   English

从文件读取Java扫描程序

[英]Java Scanner Read from File

Let me first establish the following fact: I am new to java, so please be patient. 让我首先确定以下事实:我是Java的新手,所以请耐心等待。

In my programming class, we were given an exercise to do at home using the Scanner class. 在我的编程课上,我们使用Scanner课进行了一项在家练习的练习。 The activity shows the following coding to exercise with: 该活动显示以下代码以供执行:

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());
          }

     }
}

The program seems to not be working correct. 该程序似乎无法正常工作。 I use NetBeans to run the code, and when I run the code, it does not display the data in the text file, Names.txt. 我使用NetBeans来运行代码,并且在运行代码时,它不会在文本文件Names.txt中显示数据。 Why is that? 这是为什么? The program does however Build completely without errors. 该程序确实可以完全构建而没有错误。

I have tried going through the Scanner class javadocs, but it's not helping me. 我尝试遍历Scanner类javadocs,但这对我没有帮助。

Please explain to me so that I can learn from the mistake made. 请向我解释,以便我可以从错误中学习。

Thanks, Johan 谢谢,约翰

I tried your code on my mac, and it works. 我在Mac上尝试了您的代码,并且可以正常工作。 So I thought you might input a wrong path of Names1.txt file. 因此,我认为您可能输入了Names1.txt文件错误的路径。

In Java, when you simply use "what_ever_file_name.txt" as the path of file, Java will only search the file in your source code folder. 在Java中,当您仅使用“ what_ever_file_name.txt”作为文件路径时,Java只会在源代码文件夹中搜索文件。 If nothing found, a "FILE_NOT_FOUND_EXCEPTION" will be thrown. 如果未找到任何内容,将抛出“ FILE_NOT_FOUND_EXCEPTION”。

I agree with user2170674. 我同意user2170674。 I also tried your code in a Windows machine, using Eclipse, and everything went well. 我还使用Eclipse在Windows机器上尝试了您的代码,一切顺利。 Maybe you are putting your file in the wrong path. 也许您将文件放在错误的路径中。 Two options: 两种选择:

  • you could use the full path, like (if you're using Windows) "C:\\Names1.txt"; 您可以使用完整路径,例如(如果使用Windows)“ C:\\ Names1.txt”;
  • or, a more generic solution, using JFileChooser: 或更通用的解决方案,使用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... } 

Your code looks good. 您的代码看起来不错。
Debug with a few messages. 调试一些消息。
At end, add a System.out.println() or System.out.flush() . 最后,添加System.out.println()System.out.flush()
Move exception block location to just after file use (minimise try block size) and move close() within finally block. 将异常块的位置移到文件使用后(尽量减小块的大小),然后在finally块内移动close()。
Make sure you view Netbeans output window (Window -> Output -> Output) 确保查看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.");
 }
}

Here's a working example. 这是一个工作示例。 Perhaps try using a BufferedReader. 也许尝试使用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();
        }
    }
}
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM