Write to text file without overwriting in Java

前端 未结 9 1376
失恋的感觉
失恋的感觉 2020-11-30 05:02

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 cal

9条回答
  •  忘掉有多难
    2020-11-30 05:35

    use a FileWriter instead.

    FileWriter(File file, boolean append)
    

    the second argument in the constructor tells the FileWriter to append any given input to the file rather than overwriting it.

    here is some code for your example:

    File log = new File("log.txt")
    
    try{
        if(!log.exists()){
            System.out.println("We had to make a new file.");
            log.createNewFile();
        }
    
        FileWriter fileWriter = new FileWriter(log, true);
    
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write("******* " + timeStamp.toString() +"******* " + "\n");
        bufferedWriter.close();
    
        System.out.println("Done");
    } catch(IOException e) {
        System.out.println("COULD NOT LOG!!");
    }
    

提交回复
热议问题