写入文件而不删除旧数据

发布于 2021-01-30 22:59:38

我想用Java编写一个文件而不清除(删除)该文件上的旧数据!

我运行此代码,发现每次运行后,.txt文件上的所有较旧数据都被清除了!

我的代码在这里:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {

public static void main(String[] args) {
    try {

        String content = "This is the content to write into file";

        File file = new File("/users/mkyong/filename.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
关注者
0
被浏览
74
1 个回答
  • 面试哥
    面试哥 2021-01-30
    为面试而生,有面试问题,就找面试哥。

    使用FileWriter(String filename, boolean append)可以指示在附加模式下打开文件的构造函数:

    FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                                                         //^^^^ means append
    


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看