关于可能重新使用 java 扫描仪的简单问题?

Simple issue about possible to re use java Scanner?

我还是 java 的新手,是否可以重新使用 Scanner 对象? 下面的例子是我正在读取一个文件来计算字符、单词和行数。我知道必须有一种更好的方法来仅对一个扫描仪对象进行计数,但这不是重点。我只是想知道为什么有 input.close() 但没有 input.open()input.reset 等。因为我实际上正在读取同一个文件,是否可以只创建一个 Scanner 对象并传递 3 种方法使用?谢谢

public class Test {

    /**
     * @throws java.io.FileNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("demo.java");
        Scanner input = new Scanner(file);
        Scanner input2 = new Scanner(file);
        Scanner input3 = new Scanner(file);
        int lines = 0;
        int words = 0;
        int characters = 0;

        checkCharacters(input3);
        checkLines(input);
        checkwords(input2);

    }

    private static void checkLines(Scanner input) {
        int count = 0;
        while (input.hasNext()) {

            String temp = input.nextLine();
            String result = temp;
            count++;
        }
        System.out.printf("%d lines \n", count);
    }

    private static void checkwords(Scanner input2) {
        int count = 0;
        while (input2.hasNext()) {
            String temp = input2.next();
            String result = temp;
            count++;
        }
        System.out.printf("%d words \n", count);
    }

    private static void checkCharacters(Scanner input3) {
        int count = 0;
        while (input3.hasNext()) {
            String temp = input3.nextLine();
            String result = temp;
            count += temp.length();
        }
        System.out.printf("%d characters \n", count);
    }
}

不,无法通过扫描仪上的方法重置扫描仪。如果您将 InputStream 传入扫描仪然后直接重置流,您也许可以做到这一点,但我认为这不值得。

您似乎对同一个文件进行了 3 次解析,并对同一个输入进行了 3 次处理。这似乎是在浪费处理。你不能一次执行所有 3 个计数吗?

private static int[] getCounts(Scanner input) {

   int[] counts = new int[3];

   while(input.hasNextLine()){
      String line = input.nextLine();
      counts[0]++; // lines

      counts[2]+=line.length(); //chars

      //count words
      //for simplicity make a new scanner could probably be better
      //using regex or StringTokenizer
      try(Scanner wordScanner = new Scanner(line)){
           while (wordScanner.hasNext()) {
               wordScanner.next();
               count[1] ++;  //words
           }
      }
   }

   return counts;

}

当然,面向对象的方法是 return 一个名为 Counts 的新对象,其方法为 getNumLines()getNumChars()

编辑

有一点需要注意,我的计算与您在原始问题中的计算相同。我不确定计数是否始终准确,尤其是字符,因为扫描仪可能不会 return 所有行尾字符,因此字符计数可能会关闭,如果有连续的空行,行数可能会关闭?您需要对此进行测试。

不,这是不可能的,因为正如documentation所说

void close()
           throws IOException

Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.

一旦 resourcerelaesed 就没有办法取回它,直到你有一个对它的引用,它实际上是关闭的