user2568219
user2568219

Reputation: 95

How to keep on appending logs while writing into File in SDCard?

I have written a method to print Logs in file. This is working. My only concern is that the logs are been replaced by new logs. Is there any way to keep logs appending ??

public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -d *:V";

Log.d(TAG, "command: " + command);

try{
    Process process = Runtime.getRuntime().exec(command);

    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null;
    try{
        File file = new File(filename);
        file.createNewFile();
        FileWriter writer = new FileWriter(file);
        while((line = in.readLine()) != null){
            writer.write(line + "\n");
        }
        writer.flush();
        writer.close();
    }
    catch(IOException e){
        e.printStackTrace();
    }
}
catch(IOException e){
    e.printStackTrace();
}
}

Upvotes: 0

Views: 798

Answers (2)

JiTHiN
JiTHiN

Reputation: 6588

Try this:

public static void printLog(String logData) {

    try {
        File logFile = new File(Environment.getExternalStorageDirectory(),
                "yourLog.txt");
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
                    true));
            buf.append(logData);
            buf.newLine();
            buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
              e.printStackTrace();
    }
}

You are not writing the file in Append mode. Use new FileWriter(file,true) instead of new FileWriter(file)

Upvotes: 2

Ion Aalbers
Ion Aalbers

Reputation: 8040

More easy way to write to your sdcard:

try {
    FileWriter  f = new FileWriter(Environment.getExternalStorageDirectory()+
             "/mytextfile.txt", true);
    f.write("Hello World");
    f.flush();
    f.close();
}

The boolean in the constructor of FileWriter says its only allowed to append:

http://developer.android.com/reference/java/io/FileWriter.html#FileWriter(java.io.File, boolean)

Upvotes: 1

Related Questions