![](/img/trans.png)
[英]How can I get output from subprocess.check_output if the subprocess is a java program(with Command-line arguments)?
[英]how can i obtain the output of a subprocess in java
也许它与android有一些联系,但没有多少IMO。
package com.main.app;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.widget.TextView;
public class RootPermissionActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Process p = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(p.getOutputStream());
outputStream.writeBytes("touchasd /m\n");
//codes below used to get the error output, but get nothing.
TextView suCommandMessage = (TextView)findViewById(R.id.suCommandMessage);
BufferedReader d = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String msg;
while((msg = d.readLine()) != null) {
suCommandMessage.setText(msg);
}
outputStream.writeBytes("exit \n");
p.waitFor();
} catch(IOException e) {
new AlertDialog.Builder(this)
.setTitle("Exception")
.setMessage("IOException: " + e)
.setPositiveButton("OK", null)
.show();
} catch(InterruptedException e) {
new AlertDialog.Builder(this)
.setTitle("Exception")
.setMessage("InterruptedException: " + e)
.setPositiveButton("OK", null)
.show();
}
}
}
首先,我创建一个新的进程su
以获得root权限,它只是一个运行shell命令的子进程,然后我向该子进程编写一些代码,一切正常。 然后我想获取子流程的错误输出,所以我写了一个错误的命令touchasd /m\\n
,但是我不知道如何获取子流程的错误输出,有人可以帮我吗? 谢谢。 :)
请执行以下操作来获取该过程的错误流。
BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
我没有在您的代码块中看到注释,似乎以上行和相关内容在您的代码块中被注释掉了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.