Android java InputStreamReader

时间:2016-06-24 05:25:26

标签: java android bufferedreader

我正在尝试创建一个允许我在android中发出命令并给我结果的应用程序。这似乎工作正常,但是等待一段时间以获得更多输出的命令无法正确处理。我正在尝试发出命令“su&& nmap -sS 192.168.1.1”,我得到的输出就是nmap已经启动了。有没有人知道如何获得nmap已经开始的输出,但是使用下面代码的修改版本的扫描结果。

try {
        EditText inputTxt = (EditText) findViewById(R.id.input);
        String str = inputTxt.getText().toString();
        Process command = Runtime.getRuntime().exec(str);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(command.getInputStream()));
        int read;
        char[] buffer = new char[4096];
        StringBuffer output = new StringBuffer();
        while ((read = reader.read(buffer)) > 0) {
            output.append(buffer, 0, read);
        }
        reader.close();

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(output);

    }
    catch (IOException e) {
        Log.e("Run_Command", Log.getStackTraceString(e));
    }

1 个答案:

答案 0 :(得分:-1)

我提出了另一个版本的代码。这个使用thread.sleep并且没有固定大小的缓冲区。

我得到的输出仍然是nmap已启动,而不是扫描结果,即使扫描在最终thread.sleep完成时已完成。

public void command(View view)
{
    String me;
    int a = 0;
    try {
        EditText inputTxt = (EditText) findViewById(R.id.input);
        String str = inputTxt.getText().toString();
        Process command = Runtime.getRuntime().exec(str);

        BufferedReader bReader = new BufferedReader(
                new InputStreamReader(command.getInputStream(), "UTF8"));
        //char [] me = new char[40960];
        String inputLine;
        while(1 == 1){
            if(a == 5) {
                break;}

        while ((inputLine = bReader.readLine()) != null) {
            me += inputLine + "\n";
        }
            while(bReader.readLine() == null) {
                a++;
                Thread.sleep(5000);
                if (a == 5) {
                    break;
                }
            }
                    }
        bReader.close();

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(me);

    }
    catch (IOException e) {
        Log.e("Run_Command", Log.getStackTraceString(e));
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
}