简体   繁体   中英

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

I have to write 100 random integers to a file, and display them in increasing order. PrintWriter writes them, but when I try to read from file, method hasNext() return false, and I can't understand why. I suppose the problem is with 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!");
        }

You need to flush the output stream so changes are written to the file.

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

output.flush();
...

Additionally, close flushes the stream automatically in this case - so if you tried to read the file after the try block, you would see the changes. For a PrintWriter , flush is also called whenever a newline is printed (via println or manually via printf / print ).

I believe it is usually not a good idea to have a reader and writer open simultaneously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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