写入文本文件而不用Java覆盖 [英] Write to text file without overwriting in Java

查看:236
本文介绍了写入文本文件而不用Java覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个方法,如果一个log.txt文件尚未存在,则会生成log.txt文件然后写入该文件。我遇到的问题是每次调用方法时,它都会覆盖现有的日志。如何更改方法,以便不是覆盖数据而只更新文件?

I am trying to write a method that makes a "log.txt file" if one does not already exist and then writes to the file. The problem that I am encountering is every time I call the method, it overwrites the existing log. How do I change the method so that instead of overwriting the data it just updates the file?

我的写文件方法:

    File log = new File("log.txt")
    try{
    if(log.exists()==false){
            System.out.println("We had to make a new file.");
            log.createNewFile();
    }
    PrintWriter out = new PrintWriter(log);
    out.append("******* " + timeStamp.toString() +"******* " + "\n");
    out.close();
    }catch(IOException e){
        System.out.println("COULD NOT LOG!!");
    }


推荐答案

只需更改 PrintWriter out = new PrintWriter(log); to

PrintWriter out = new PrintWriter(new FileWriter(log, true));

这篇关于写入文本文件而不用Java覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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