出于某种原因使用FileWriter和BufferedWriter清除文件? [英] Using FileWriter and BufferedWriter clearing file for some reason?

查看:461
本文介绍了出于某种原因使用FileWriter和BufferedWriter清除文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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由JFileChooser决定。

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

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


推荐答案

这是因为构造函数 FileWriter 如果文件已存在,则使用截断文件。

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

这篇关于出于某种原因使用FileWriter和BufferedWriter清除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆