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
You're only invoking write once, and you want to write to the file immediately. You don't need a BufferedWriter or a PrintWriter. They're overhead. Also, close should be invoked from a finally{} block, since you still need to close it if you have an error.
public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string + "\n";
Writer out = null;
try {
out = new FileWriter(logFile, true);
out.write(text, 0, text.length());
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
} finally {
if (out != null){
out.close();
}
}
}
Only declare a BufferedWriter if you're going to be making multiple writes while the file is open. The purpose of the BufferedWriter is to improve the efficiency of multiple writes by keeping track of what has been input vs what's already been flushed.
Another issue I see is that because this is a static method and the writer isn't static, multiple invocations could try to simultaneously call writeToLog.
If you're using Java 7 or higher, you can simplify that a lot using a try with resources statement to auto-close your writer:
public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string + "\n";
try (FileWriter out = new FileWriter(logFile, true)) {
out.write(text, 0, text.length());
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
}
}
You may want to consider keeping the writer open if you're going to log lines to it every second possibly multiple times, since opening/closing causes a lot of overhead. It also insures that all of your calls to writeToLog() are being sent to the same writer, in order.
private static final PrintWriter logWriter =
new PrintWriter(new BufferedWriter(new FileWriter(logFile, true)));
private static int flushCounter = 0;
private static final int flushFrequency = 5; // Flush the buffer every 5 lines
public static void writeToLog(Context context, String string) {
String text = getTimestamp() + " " + string + "\n";
try {
logWriter.write(text, 0, text.length());
} catch (IOException e) {
Log.d(Constants.APP_NAME, e.toString());
} finally {
flushCounter++;
if (flushCounter > flushFrequency){ // flush every 5 lines
logWriter.flush();
flushCounter = 0;
}
}
}
public void close(){
logWriter.close();
}
You can call close() from a finally{} block in your invoking code to clean up your logWriter.