1

我正在尝试这段代码

public String ReadFromCMD()
        {
             ProcessBuilder cmd;
             String result="";
             //int resultshow = 0;

             try{
              String[] args = {"/system/bin/top -m 10 -n 1"};

                 cmd = new ProcessBuilder(strCmdArgs);

              Process process = cmd.start();
              InputStream in = process.getInputStream();


              BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));
                int read;
                char[] buffer = new char[4096];
                StringBuffer output = new StringBuffer();

                process.waitFor();

                while ((read = reader.read(buffer)) > 0) {
                    output.append(buffer, 0, read);
                }
                reader.close();


               in.close();

             } catch(Exception ex){
              ex.printStackTrace();
             }
             return result;
        }

错误来了:

03-25 09:57:36.885: W/System.err(30300): java.io.IOException: Error running exec(). 
Command: [/system/bin/top -m 10 -n 1] Working Directory: null Environment: 
[ANDROID_SOCKET_zygote=10, SECONDARY_STORAGE=/storage/extSdCard:/storage/UsbDriveA:/storage
/UsbDriveB:/storage/UsbDriveC:/storage/UsbDriveD:/storage/UsbDriveE:/storage/UsbDriveF, 
ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/storage/sdcard0, ANDROID_ASSETS=/system/app, 
PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, ASEC_MOUNTPOINT=/mnt/asec, 
LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:/system/framework/core-
junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework
/framework.jar:/system/framework/framework2.jar:/system/framework/android.policy.jar:
/system/framework/services.jar:/system/framework/apache-xml.jar:/system/framework
/sec_edm.jar:/system/framework/seccamera.jar, ANDROID_DATA=/data, LD_LIBRARY_PATH=/vendor
/lib:/system/lib, ANDROID_ROOT=/system, ANDROID_PROPERTY_WORKSPACE=9,66560, 
VIBE_PIPE_PATH=/dev/pipes]
03-25 09:57:36.885: W/System.err(30300):    at java.lang.ProcessManager.exec(ProcessManager.java:211)
03-25 09:57:36.885: W/System.err(30300):    at java.lang.ProcessBuilder.start(ProcessBuilder.java:195)

此错误出现在行

Process process = cmd.start();

请帮我解决这个问题

4

1 回答 1

1

这个:

String[] args = {"/system/bin/top -m 10 -n 1"};

意味着您的可执行文件是目录中命名top -m 10 -n 1的文件/system/bin

您想要的是top在该目录中命名的可执行文件,带有-m 10 -n 1四个单独的参数:

String[] args = {"/system/bin/top", "-m", "10", "-n", "1"};

或者,由于这些组件都不包含空格,因此您可以“作弊”并编写如下内容:

String[] args = "/system/bin/top -m 10 -n 1".split(" ");

这是相同的(它仍然创建一个由五个字符串组成的数组),但可以说更容易阅读。

于 2013-03-25T04:45:36.260 回答