【问题标题】:Executing terminal command from java program从java程序执行终端命令
【发布时间】:2018-08-21 01:01:51
【问题描述】:

我正在用 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 程序中的终端命令创建文件存在问题。如果您有任何想法,请提供帮助。

【问题讨论】:

    标签: java android file terminal command


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      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);
          }
      }
      

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

      【讨论】:

        猜你喜欢
        • 2014-12-15
        • 2015-12-17
        • 1970-01-01
        • 2010-09-29
        • 2020-07-24
        • 2015-08-16
        • 2015-01-27
        • 2013-02-27
        相关资源
        最近更新 更多