我试图将URL中的文本以35行为单位分批写入文本文件,按回车键继续下一批35行。如果我不尝试以35行为一批的方式写入文件,它的工作效果很好,并将所有内容写入文本文件。但是当我尝试使用if语句以35行为单位打印时,除非我按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();
}
我不懂Java,但在.NET中也有很类似的概念。我认为这里有几件事需要考虑。
BufferWriter
它不会立即写入文件,它的作用--正如其名称所示--是一个缓冲区,随着时间的推移收集写入请求,然后以批处理的方式进行。BufferWriter
有一个 flush
方法来立即刷新 "排队 "写到文件的内容--所以当你达到35时,我会这么做(每次写时都不要刷新)。
另外。BufferedReader
和 BufferedWriter
是可以闭合的,所以要确保将它们包裹在一个 try
语句,以确保资源被正确解锁清除。