bufferedwriter - 为什么 BufferedWriter 不会将 URL 内容写入文本文件?
问题描述
我正在尝试将 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();
}
解决方案
我不了解 Java,但 .NET 中有非常相似的概念。我认为这里有几件事需要考虑。
BufferWriter
不会立即写入文件,它充当 - 顾名思义 - 作为缓冲区,随着时间的推移收集写入请求,然后批量执行。BufferWriter
有一种flush
方法可以立即将“排队”的写入刷新到文件中 - 所以当你达到 35 时我会这样做(不要在每次写入时刷新)。
此外,BufferedReader
并且BufferedWriter
是可关闭的,因此请确保将它们包装在try
语句中以确保资源正确解锁/清除。
推荐阅读
- sapui5 - MessagePopover 片段中的动态链接未显示
- ssl - 如何在码头 9.3.12 中启用 ssl?
- bigdata - Azkaban 是大数据解决方案调度程序的好选择吗?
- c# - WPF ListBox 多选不会在模型上引发 SelectedItem
- postgresql - Ubuntu 18.04 中的 PostgreSQL 奇怪行为
- c++ - 大字符串的 fprintf/fputs 与 cout 性能
- wpf - 直接在代码(视图)中访问 xaml 文件中的值
- apdu - 如何确定 SIM 卡上远程文件管理的 SPI?
- twitter-bootstrap - 响应式缩略图滑块一张一张地移动图像
- python - 为什么 scipy 为结果应该为零的积分提供非零结果?