Reputation: 50
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!");
}
Upvotes: 0
Views: 39
Reputation: 14967
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.
Upvotes: 3