0

我已经编写了一种在文件中打印日志的方法。这是有效的。我唯一担心的是日志被新日志替换。有什么办法可以保持日志附加?

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

2 回答 2

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)

于 2013-07-12T12:16:58.253 回答
1

写入 sdcard 的更简单方法:

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 , boolean)

于 2013-07-12T11:57:25.373 回答