阅读苏进程中命令的输出命令、苏进

由网友(孤独成瘾)分享简介:首先,我将present我的情况。我需要在我的Andr​​oid应用程序执行su命令,效果很好。然后,我需要执行ls命令和读取输出。我通过获取从俗过程中的输出流,写我的命令把它做起来。firstly I will present my situation.I need to execute "su" comman...

首先,我将present我的情况。 我需要在我的Andr​​oid应用程序执行su命令,效果很好。然后,我需要执行ls命令和读取输出。我通过获取从俗过程中的输出流,写我的命令把它做起来。

firstly I will present my situation. I need to execute "su" command in my android app and it works well. Then I need to execute "ls" command and read the output. I'm doing it by getting the output stream from the "su" process and writing my command into it.

和这里不用的问题。如何阅读LS过程的输出?我想说明的是苏Process对象。获取输入流,从它提供什么,因为苏不写任何东西。但是,LS不,我不知道如何访问它的输出消息。

And here goes the question. How to read the output of the "ls" process? All I have is the "su" Process object. Getting the input stream from it gives nothing, because "su" doesn't write anything. But "ls" does and I don't know how to access its output messages.

我已经搜查了许多网站,但我没有找到任何解决方案。也许有人会帮我:)

I have searched many sites but I didn't find any solution. Maybe someone will help me:)

问候

推荐答案

好吧,我已经找到了解决办法。它应该是这样的:

Ok, I've found a solution. It should look like this:

Process p = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
//from here all commands are executed with su permissions
stdin.writeBytes("ls /datan"); // n executes the command
InputStream stdout = p.getInputStream();
byte[] buffer = new byte[BUFF_LEN];
int read;
String out = new String();
//read method will wait forever if there is nothing in the stream
//so we need to read it in another way than while((read=stdout.read(buffer))>0)
while(true){
    read = stdout.read(buffer);
    out += new String(buffer, 0, read);
    if(read<BUFF_LEN){
        //we have read everything
        break;
    }
}
//do something with the output

希望这将是有益的人。

Hope it will be helpful for someone

阅读全文

相关推荐

最新文章