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!