Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

Write to text file without overwriting in Java

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?

My Write File Method:

    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() +"******* " + "
");
    out.close();
    }catch(IOException e){
        System.out.println("COULD NOT LOG!!");
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just change PrintWriter out = new PrintWriter(log); to

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...