简体   繁体   中英

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();
}
}

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM