Search code examples
javaiofilewriterbufferedwriter

Using FileWriter and BufferedWriter clearing file for some reason?


For some reason, when I create a new BufferedWriter and FileWriter in my program (Even if I haven't used it to write anything yet), it clears the file I have selected of all it's text.

selectedFile is determined by a JFileChooser.

public static File selectedFile;

    public static void Encrypt() throws Exception {

    try {
        //if I comment these two writers out the file is not cleared.
        FileWriter fw = new FileWriter(selectedFile.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

        List<String> lines = Files.readAllLines(Paths.get(selectedFile.toString()),
                Charset.defaultCharset());
        for (String line : lines) {
            System.out.println(line);
            System.out.println(AESencrp.encrypt(line));

            /*file is cleared regardless of whether or not these are commented out or
             * not, as long as I create the new FileWriter and BufferedWriter the file
             * is cleared regardless.*/

            //bw.write(AESencrp.encrypt(line));
            //bw.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

AESencrp.encrypt is just an encrypting class I have, it won't affect it. If I create a new FileWriter and BufferedWriter then this loop isn't even run (At least I do not believe so, as I don't get the encryption of line or the original contents of the file printed, which prints if I haven't created the new FileWriter/BufferedWriter.)

        for (String line : lines) {
            System.out.println(line);
            System.out.println(AESencrp.encrypt(line));

            /*file is cleared regardless of whether or not these are commented out or
             * not, as long as I create the new FileWriter and BufferedWriter the file
             * is cleared regardless.*/

            //bw.write(AESencrp.encrypt(line));
            //bw.close();
        }

Solution

  • This is because the constructor of FileWriter you are using truncates the file if it already exists.

    If you want to append the data instead, use:

    new FileWriter(theFile, true);