我看到有人抱怨 Logcat 只输出最后一行。我想问一个保留的问题,我怎样才能产生这个只输出最后一行的条件?
这就是我通过启动线程来读取日志的方式。
public class ReadLog implements Runnable{
private boolean running = true;
public void stop(){
running = false;
}
@Override
public void run() {
Process proc = null;
try {
//Runtime.getRuntime().exec("/system/bin/logcat -c");
proc = Runtime.getRuntime().exec("/system/bin/logcat ");
}catch(IOException e) {
e.printStackTrace();
}
if(proc != null){
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line= null;
try {
while((line=reader.readLine())!=null && running){
if(line.contains("specific word")){
doSomething();//do something base on log
running = false;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally{
proc.destroy();
}
}
}
}
我只想阅读最新的一行。问题是它会触发 doSomething() 即使“特定单词”不在最后一行,除非我添加Runtime.getRuntime().exec("/system/bin/logcat -c");
该行以在开始运行之前清除日志。
确实,我可以再添加一个while((line=reader.readLine())!=null && running){}
,让 BufferedReader 在开始运行之前转到最后一行,但这可能需要很长时间而且为时已晚。
我试过Runtime.getRuntime().exec("/system/bin/logcat | tail -n 1");
但没有tail
不接受标准输入的运气。我要求任何可以快速输出标准输出最后一行的命令,就像tail -n 1 FILE
.