【发布时间】:2020-04-22 23:52:21
【问题描述】:
我正在尝试将 URL 中的文本分批写入 35 行的文本文件,按 Enter 以继续下一批 35 行。如果我不尝试分批写入 35 行文件,它会很好地将所有内容写入文本文件。但是,当我尝试使用 if 语句分批打印 35 个时,除非我按 Enter 大约 15 次,否则它不会打印到文件中。即便如此,它也不会打印所有内容。我似乎与 if 语句有关,但我无法弄清楚。
String urlString = "https://www.gutenberg.org/files/46768/46768-0.txt";
try {
URL url = new URL(urlString);
try(Scanner input = new Scanner(System.in);
InputStream stream = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\mattj\\Documents\\JuliusCeasar.txt"));) {
String line;
int PAGE_LENGTH = 35;
int lineCount = 0;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line + "\n");
lineCount++;
if (lineCount == PAGE_LENGTH){
System.out.println();
System.out.println("- - - Press enter to continue - - -");
input.nextLine();
lineCount = 0;
}
}
}
} catch (MalformedURLException e) {
System.out.println("We encountered a problem regarding the following URL:\n"
+ urlString + "\nEither no legal protocol could be found or the "
+ "string could not be parsed.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Attempting to open a stream from the following URL:\n"
+ urlString + "\ncaused a problem.");
e.printStackTrace();
}
【问题讨论】:
标签: bufferedwriter