簡體   English   中英

將整數寫入文件並讀取它們,hasNext()返回false

[英]Writing ints to a file and reading them, hasNext() return false

我必須將100個隨機整數寫入文件,並以遞增順序顯示它們。 PrintWriter編寫它們,但是當我嘗試從文件讀取時,方法hasNext()返回false,而我不明白為什么。 我想問題出在PrintWriter。

try(PrintWriter output = new PrintWriter(file);
                Scanner input = new Scanner(file)) {

            for (int i = 0; i < 100; i++) {
                output.print((int)(Math.random() * 101) + " ");
            }

            int[] numbers = new int[100];
            int i = 0;
            while (input.hasNextInt()) {
                numbers[i++] = input.nextInt();
            }

            Arrays.sort(numbers);
            for (int n : numbers)
                System.out.println(n);

        } catch (FileNotFoundException ex) {
            System.out.println("Cannot find the file!");
        }

您需要flush輸出流,以便將更改寫入文件。

...
for (int i = 0; i < 100; i++) {
    output.print((int) (Math.random() * 101) + " ");
}

output.flush();
...

此外,在這種情況下, close自動刷新流-因此,如果嘗試在try塊之后讀取文件, 則會看到更改。 對於PrintWriter ,每當打印換行符時(通過println或通過printf / print手動),也會調用flush

我認為同時打開讀者和作家通常不是一個好主意。

暫無
暫無

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

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