【问题标题】:FileWriter not appending to existing fileFileWriter 不附加到现有文件
【发布时间】:2017-04-27 23:00:06
【问题描述】:

我正在编写一个方法,它接收 Twitter 的 Status 对象的 List 作为参数,打开一个包含 String 推文表示的日志文件,检查是否有任何 String 表示 @987654325 @ 对象已写入文件 - 如果是,则将其从列表中删除,否则将 Status 附加到文件中。

一切正常,直到我尝试写入文件。什么都没有写。我被引导相信这是由于在两个不同的地方打开文件的方法:new File("tweets.txt")new FileWriter("tweets.txt, true)

这是我的方法:

    private List<Status> removeDuplicates(List<Status> mentions) {
        File mentionsFile = new File("tweets.txt");
        try {
            mentionsFile.createNewFile();
        } catch (IOException e1) {
            // Print error + stacktrace
        }

        List<String> fileLines = new ArrayList<>(); 
        try {
            Scanner scanner = new Scanner(mentionsFile);
            while (scanner.hasNextLine()) {
                fileLines.add(scanner.nextLine());
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            // Print error + stacktrace
        }

        List<Status> duplicates = new ArrayList<>();    
        for (Status mention : mentions) {
            String mentionString = "@" + mention.getUser().getScreenName() + " \"" + mention.getText() + "\" (" + mention.getCreatedAt() + "\")";
            if (fileLines.contains(mentionString)) {
                duplicates.add(mention);
            } else {
                try {
                    Writer writer = new BufferedWriter(new FileWriter("tweets.txt", true));
                    writer.write(mentionString);
                } catch (IOException e) {
                    // Print error + stacktrace
                }

            }
        }

        mentions.removeAll(duplicates);
        return mentions;
    }

【问题讨论】:

    标签: java file filewriter bufferedwriter


    【解决方案1】:

    我在这里写了一些想法看你的代码。

    请记住始终关闭对象ReaderWriter

    看看try-with-resources statement

    try (Writer writer = new BufferedWriter(new FileWriter("tweets.txt", true))) {
       writer.write(mentionString);
    } catch (IOException e) {
       // Print error + stacktrace
    }
    

    读取List&lt;String&gt;中的整个文件:

    List<String> lines = Files.readAllLines(Paths.get("tweets.txt"), StandardCharsets.UTF_8);
    

    再一次,我认为在你正在阅读的同一个文件中写入是一种不好的做法。

    如果您没有特定的限制,我建议您写入不同的文件。

    但如果你真的想要这种行为,那么几乎没有其他选择。

    1. 创建一个临时文件作为输出,当您成功完成处理后,使用Files.move(from, to) 将其移至旧文件。

    【讨论】:

    • 为了测试这是否是导致问题的原因,我将其更改为 Writer writer = new BufferedWriter(new FileWriter("tweets2.txt", true)); 并创建 tweets2.txt,但仍然没有向其中写入任何内容。
    • 你不要刷新并关闭 writer
    • 所以使用try-with-resources 语句我不需要显式关闭资源,它是自动完成的吗?那么潮红呢?我认为仍然必须手动完成?
    • 没有。仅在您希望确保在特定时刻进行物理写入但通常不需要这样做的特定情况下手动刷新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 2012-07-12
    • 2015-04-29
    • 2010-11-16
    • 1970-01-01
    相关资源
    最近更新 更多