0

I try to build a simple android app that shows text on the screen and has a button. I created a log file at the onCreate() method and would like to append the new log line to the document upon the click on the button. I used the following code in both onCreate() and onButtonClick() events:

try{
    if(!file.exists()){
        System.out.println("We had to make a new file.");
        file.createNewFile();
    }

    FileWriter fileWriter = new FileWriter(file, true);

    String ts = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
    Log.d("LOGGER" , ts);

    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write("******* " + ts.toString() +" ******* " + "\n");

    bufferedWriter.close();
    fileWriter.close();

    System.out.println("Done");

} catch(IOException e) {
    System.out.println("COULD NOT LOG!!");
}

The file is created and is filled with the data uppon onCreate(), the problem is that when I call onButtonClick() the new log line is not appended to the log file despite the fact I specified true in the FileWriter constructor: new FileWriter(file, true).

Could you point me, why my log is not appended with the new lines?

Mike
  • 14,010
  • 29
  • 101
  • 161
Jasmin F
  • 9
  • 3
  • Show us the code where you attach the listener to the button. – takendarkk Aug 16 '17 at 12:42
  • is the button click function invoked when you click the button? – Samuel Robert Aug 16 '17 at 12:42
  • I think this link may help you [Append to file](https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – K Sathish Aug 16 '17 at 12:54
  • try this also https://stackoverflow.com/questions/27415074/android-save-to-file-txt-appending – K Sathish Aug 16 '17 at 12:58
  • I tried your code but the file is not created... – Jasmin F Aug 16 '17 at 13:10
  • I tried to use FileWriter as well as bufferwriter- at the first run it works fine (creating the file, writing to it and append data) but when I want to append data when I push a button (i.e. document the exact time I pushed the data into the file) it does not work... – Jasmin F Aug 16 '17 at 14:27

0 Answers0