【问题标题】:Why won't BufferedWriter write URL content to text file?为什么 BufferedWriter 不会将 URL 内容写入文本文件?
【发布时间】: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


    【解决方案1】:

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

    BufferWriter 不会立即写入文件,它就像名称所暗示的那样充当缓冲区,随着时间的推移收集写入请求,然后批量执行。 BufferWriter 有一个 flush 方法可以立即将“排队”的写入刷新到文件中——所以当你达到 35 时我会这样做(永远不要在每次写入时刷新)。

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

    【讨论】:

      猜你喜欢
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多