FileWriter未附加到现有文件

时间:2017-04-27 23:00:06

标签: java file filewriter bufferedwriter

我正在编写一个方法,它接收ListStatus个对象作为参数,打开一个包含String推文表示的日志文件,检查是否有任何String 1}} Status个对象的表示已写入文件 - 如果是,则将其从列表中删除,否则会将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;
    }

1 个答案:

答案 0 :(得分:0)

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

请务必关闭对象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<String>中的整个文件:

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

而且,我认为这是一个不好的做法,写在您正在阅读的同一个档案中。

如果你没有特定的约束,我建议写一个不同的文件。

但如果你真的想要这种行为,那么很少有替代方案。

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