出于某种原因使用FileWriter和BufferedWriter清除文件?

时间:2013-06-21 21:39:32

标签: java io filewriter bufferedwriter

出于某种原因,当我在我的程序中创建一个新的BufferedWriter和FileWriter时(即使我还没有使用它来编写任何东西),它会清除我选择的所有文本的文件。

selectedFile由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只是我的加密类,它不会影响它。如果我创建一个新的FileWriter和BufferedWriter,那么这个循环甚至不会运行(至少我不相信,因为我没有得到行的加密或打印文件的原始内容,如果我没有打印那么打印创建了新的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();
        }

3 个答案:

答案 0 :(得分:3)

这是因为您使用的FileWriter构造函数会截断该文件(如果该文件已存在)。

如果您想要追加数据,请使用:

new FileWriter(theFile, true);

答案 1 :(得分:2)

听起来你想要附加到文件,而不是覆盖它。使用正确的FileWriter constructor that takes a boolean on whether to append

FileWriter fw = new FileWriter(selectedFile.getAbsoluteFile(), true);

您使用的构造函数没有boolean,默认为“覆盖”模式。在覆盖模式下创建FileWriter后,它会清除文件,以便从头开始编写。

传递true作为第二个参数将允许您追加而不是覆盖。

答案 2 :(得分:0)

你打开它进行写入(用于附加使用带有append选项的构造函数)。你还期待还会发生什么? 此外,您的已评注close()位于错误的位置。它应该在循环之外。