如何在SDCard中写入文件时继续附加日志?

时间:2013-07-12 11:48:23

标签: android logging

我写了一个方法来打印文件中的日志。这很有效。我唯一担心的是日志已被新日志替换。有没有办法保持日志附加?

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

2 个答案:

答案 0 :(得分:2)

试试这个:

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

您没有在追加模式下编写文件。 使用new FileWriter(file,true)代替new FileWriter(file)

答案 1 :(得分:1)

更简单的方法来写你的SD卡:

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

FileWriter构造函数中的布尔值表示只允许附加:

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