从java程序执行终端命令

时间:2018-03-12 21:43:21

标签: java android file terminal command

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

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缓冲区,第二个启动猴子测试,第三个清除报告并将其打印到文件中。前两个确实是我想要的,但第三个却没有。当我将第三个命令中创建文件的部分转到另一个命令时,它也会停止工作。我想从java程序通过terminal命令创建文件存在问题。如果您有任何想法,请帮助。

2 个答案:

答案 0 :(得分:0)

这可能是出于安全考虑。 Java可能没有使用此文件夹的权限,并且没有读写权限。如果这是问题,您应该授予它权限

答案 1 :(得分:0)

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

输出如下:                总共使用免费共享缓存/缓存Mem:15G 4,8G 7,9G 561M
  2,7G 9,7G交换:7,6G 0B 7,6G