使用运行时类执行"adb logcat"命令



我试图将logcat内容放入JTextPane。我使用下面的代码,希望它会返回的内容作为字符串,但它冻结,也不会产生错误。

Process exec = null;
    try {
        exec = Runtime.getRuntime().exec("adb logcat -d");
        InputStream errorStream = exec.getErrorStream();
        BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream));
        String errorLine;
        while ((errorLine = ebr.readLine()) != null) {
            System.out.println("[ERROR] :- " + errorLine);
        }
        if (exec.waitFor() == 0) {
            InputStream infoStream = exec.getInputStream();
            InputStreamReader isr = new InputStreamReader(infoStream);
            BufferedReader ibr = new BufferedReader(isr);
            String infoLine;
            while ((infoLine = ibr.readLine()) != null) {
                System.out.println("[INFO] :- " + infoLine);
            }
        }
    } catch (IOException | InterruptedException ex) {
        ex.printStackTrace();
    } finally {
        if (exec != null) {
            exec.destroy();
        }
    }

我参考了一些教程,但他们不能解决我的问题。这有错吗?是否有其他方法获得logcat内容作为一个字符串编程?如果这是个愚蠢的问题,我很抱歉。

您看到的问题是,您正在尝试处理命令流并等待执行进程,所有这些都在同一个线程中。它阻塞是因为读取流的进程正在等待进程,而你正在丢失流输入。

你要做的是在另一个线程中实现读取/处理命令输出(输入流)的函数,并在启动进程时启动该线程。

第二,您可能想要使用ProcessBuilder而不是Runtime.exec

像这样的东西可以做你想做的:

public class Test {
    public static void main(String[] args) throws Exception {            
        String startDir = System.getProperty("user.dir"); // start in current dir (change if needed)
        ProcessBuilder pb = new ProcessBuilder("adb","logcat","-d");
        pb.directory(new File(startDir));  // start directory
        pb.redirectErrorStream(true); // redirect the error stream to stdout
        Process p = pb.start(); // start the process
        // start a new thread to handle the stream input
        new Thread(new ProcessTestRunnable(p)).start();
        p.waitFor();  // wait if needed
    }
    // mimics stream gobbler, but allows user to process the result
    static class ProcessTestRunnable implements Runnable {
        Process p;
        BufferedReader br;
        ProcessTestRunnable(Process p) {
            this.p = p;
        }
        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(p.getInputStream());
                br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null)
                {
                    // do something with the output here...                        
                }
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

最新更新