我在将适当的日志从logcat写入android中的文本文件时遇到困难。 以下是我将logcat日志写入文件的代码。
public void readLogs(String logCode) {
File filename = new File(Environment.getExternalStorageDirectory() ,"/AppLogs");
if(!filename.exists())
{
// Make it, if it doesn't exit
filename.mkdirs();
}
final File file = new File(filename, "LogcatFile.log");
FileWriter fw = null;
BufferedWriter bw = null;
try {
String[] cmd = new String[]{"logcat","-d"};
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line;
while((line = bufferedReader.readLine()) != null)
{
log.append(line);
log.append("\n");
}
//Convert log to string
final String logString = log.toString();
System.out.println("WRITING LOGS");
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(logString);
bw.flush();
bw.close();
System.out.println("DONE");
} catch (IOException e) {
e.printStackTrace();
}
}
问题是,每当应用程序进入主屏幕或登录屏幕时,都会调用上述功能,因此它将旧的日志集与新的日志一起写入。例如,假设如果11:20处的第1行已经写入LogcatFile.log中,则下一次它不应重复同一行。基本上是从文件中删除重复的日志。我尝试了许多logcat命令都无济于事,如果有人可以帮助的话,这真的很有帮助
谢谢