Writing String to Text File

后端 未结 6 1680
太阳男子
太阳男子 2021-01-29 01:21

I am saving a log to a .txt file on the sdcard but once there is two lines saved, it overwrites it and starts over?

Here is my code:

public static Strin         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 01:41

    You can simply use FileWriter without all the chained other writers. Be sure to call flush(), as this ensures to write all buffered contents to the file.
    If this still doesn't work, check you error output.

    public static void writeToLog(Context context, String string) {
        String text = getTimestamp() + " " + string + "\n"; //newline here
    
        Writer out;
        try {
            out = new FileWriter(logFile, true);
            out.append(text);
            out.flush();        //ensure that all buffered characters are written to the target
        } catch (IOException e) {
            Log.d(Constants.APP_NAME, e.toString());
        } finally {
            if (out != null) {
                out.close();    //ensure writer is closed
            }
        }
    }
    

提交回复
热议问题