I'm trying to read the text contents off of a given URL, then print the contents, as well as write it to a text file using BufferedWriter. I need to include a code block that allows only 35 lines of text to be printed out at a time until the user presses enter using an instance of Scanner, but write the entire text file immediately. All of this must be done within a try-with-resource block. Here is my code:
try(InputStream stream = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))){
Scanner input = new Scanner(System.in);
String newLine;
int PAGE_LENGTH = 1;
while(((newLine = reader.readLine()) != null)) {
writer.write(newLine + "\n");
//writer.flush();
if(PAGE_LENGTH % 35 == 0) {
System.out.println("\n- - - Press Enter to Continue - - -");
input.nextLine();
}
else {
System.out.println(newLine);
PAGE_LENGTH++;
}
}
writer.close();
}
Prior to implementing the 35 line limit restriction, the writer was correctly writing a text file. I tried adding writer.flush();
in the loop, which resulted in only 35 lines being written, so I know that the problem occurs as soon as the 'if' statement is triggered (it must write several hundred lines of text). I noticed that if I comment out input.nextLine();
that the writer functions again.
How is the Scanner instance preventing BufferedWriter from writing the text file? What am I not considering? Any help/feedback would be greatly appreciated!
How is the Scanner instance preventing BufferedWriter from writing the text file?
Well, then I would say that it is simply because input.nextLine
blocks your program, so that you have the time to open the file and check if anything is written.
If you don't flush
, nothing will be actually written until the buffer is full (and 35 lines of your text file doesn't fill the buffer apparently), or until you close the file. This is the main feature of a buffered writer, as opposed to a non-buffered one.
It doesn't matter whether you have a scanner or not. It's just that without a scanner, the program runs too quickly that you can only check the file after it has been closed, at which point everything would have been written into it.
Also, you should increment PAGE_LENGTH
no matter which branch of the if statement is executed, otherwise it will keep hitting the "if" branch, waiting for you to press enter, once PAGE_LENGTH
reaches 35.
if(PAGE_LENGTH % 35 == 0) {
System.out.println("\n- - - Press Enter to Continue - - -");
input.nextLine();
}
else {
System.out.println(newLine);
}
// move this outside of the if statement!
PAGE_LENGTH++;