有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓从java程序执行终端命令

我正在用java编写一个程序,在安卓虚拟设备上进行monkey测试。在这个程序中,我运行以下三个命令

Runtime rt = Runtime.getRuntime();
Process clear = rt.exec("/Users/<username>/Library/Android/sdk/platform-tools/adb logcat -c");
Process monkey = rt.exec("/Users/<username>/Library/Android/sdk/platform-tools/adb shell monkey -p gy.softwaretesting1 --throttle 200 200");
Process report = rt.exec("/Users/<username>/Library/Android/sdk/platform-tools/adb logcat -d *:E | grep AndroidRuntime >> /Users/<username>/Documents/workspace/SoftwareTesting/fileReport.txt");

第一个清除logcat缓冲区,第二个启动monkey测试,第三个获取crush报告并将其打印到文件中。前两个完全符合我的要求,而第三个则不行。当我在第三个命令中扮演创建文件的角色时,它也会停止工作。我想通过java程序中的terminal命令创建文件可能有问题。如果你有任何想法,请帮忙


共 (1) 个答案

  1. # 1 楼答案

    package com.gmail.jackkobec.java.core;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    /**
     * @Author Jack <jackkobec>
     */
    public class ExecuteTerminalCommandsFromJava {
    
        public static void main(String[] args) throws IOException {
            // Gets runtime
            Runtime runtime = Runtime.getRuntime();
            // Declare a command with parameters as string array
            String[] commandWithParameters = {"free", "-h"};
            // Execute command and get it process  
            Process commandExecuteProcess = runtime.exec(commandWithParameters);
    
            // Gets input stream from process, convert it to buffered reader
            BufferedReader lineReader = new BufferedReader(new InputStreamReader(commandExecuteProcess.getInputStream()));
            // Read line by line from process input stream decorated as buffered reader
            lineReader.lines().forEach(System.out::println);
    
            // Gets errors input stream from process, convert it to buffered reader
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(commandExecuteProcess.getErrorStream()));
            // Read line by line from process errors input stream decorated as buffered reader
            errorReader.lines().forEach(System.out::println);
        }
    }
    

    Output is like: total used free shared buff/cache available Mem: 15G 4,8G 7,9G 561M
    2,7G 9,7G Swap: 7,6G 0B 7,6G