如何"顶级 m 10-n 1" 命令输出将保存到字符串在 Android 代码吗?

标签: shell Android
发布时间: 2014/9/12 16:49:53
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想这段代码

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

请帮我解决这个问题

解决方法 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"};

另外,因为没有这些组件包含 space ,你可以有点"欺骗",写东西,如:

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

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

官方微信
官方QQ群
31647020