簡體   English   中英

我如何在Java中獲取子流程的輸出

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM