首页 > 解决方案 > 为什么 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();
    }

标签: bufferedwriter

解决方案


我不了解 Java,但 .NET 中有非常相似的概念。我认为这里有几件事需要考虑。

BufferWriter不会立即写入文件,它充当 - 顾名思义 - 作为缓冲区,随着时间的推移收集写入请求,然后批量执行。BufferWriter有一种flush方法可以立即将“排队”的写入刷新到文件中 - 所以当你达到 35 时我会这样做(不要在每次写入时刷新)。

此外,BufferedReader并且BufferedWriter是可关闭的,因此请确保将它们包装在try语句中以确保资源正确解锁/清除。


推荐阅读