Search code examples
javafilefilewriterbufferedwriter

FileWriter not appending to existing file


I am writing a method that takes in a List of Twitter Status objects as a parameter, opens a log file containing String represenatations of Tweets, checks if any of the String representations of the Status objects are already written to the file - if so, it removes them from the list, if not it appends the Status to the file.

Everything is working up until I attempt to write to the file. Nothing is being written at all. I am led to believe that it is due to the method having the file open in two different places: new File("tweets.txt") and new FileWriter("tweets.txt, true).

Here is my method:

    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;
    }

Solution

  • I wrote here few thoughts looking your code.

    Remember to always close the object Reader and Writer.

    Have a look at try-with-resources statement :

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

    To read an entire file in a List<String>:

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

    And again, I think it's a bad practice write in the same file you're reading of.

    I would suggest to write in a different file if you don't have a particular constraint.

    But if you really want have this behavior there are few alternative.

    1. Create a temporary file as output and, when you process is successfully completed, than move it to the old one using Files.move(from, to).