簡體   English   中英

關於可以重新使用Java Scanner的簡單問題?

[英]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次相同的輸入。 這似乎是在浪費處理時間。 您不能一次執行全部三個計數嗎?

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;

}

當然,面向對象的方式將是使用getNumLines()getNumChars()等方法返回一個名為Counts類的新對象。

編輯

需要注意的一件事是,我將計算與您在原始問題中所做的相同。 我不確定計數是否總是准確的,尤其是字符,因為Scanner可能不會返回所有行尾字符,因此如果連續有空白行,字符計數可能會關閉並且行數可能會關閉? 您需要對此進行測試。

不,這是不可能的,因為如文檔所述

void close()
           throws IOException

關閉此流並釋放與其關聯的所有系統資源。 如果流已經關閉,則調用此方法無效。

relaesed resource relaesed ,就無法取回它, relaesed您對它的引用實際上已關閉

暫無
暫無

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

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