【问题标题】:Android java InputStreamReaderAndroid java InputStreamReader
【发布时间】:2016-06-24 05:25:25
【问题描述】:

我正在尝试制作一个允许我在 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));
    }

【问题讨论】:

  • 可能su只是在等待密码?
  • 您需要关闭作为进程输入的输出流。

标签: java android bufferedreader


【解决方案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();
    }
}

【讨论】:

  • 毫无意义。一旦readLine() 返回null,就是这样。你可以从现在睡到世界末日,但永远不会有任何输入。
  • 总有办法获取输出吧?我可能一直在用错误的方式做这件事?
猜你喜欢
  • 2011-08-16
  • 2015-08-12
  • 2014-09-22
  • 1970-01-01
  • 2015-01-04
  • 2014-04-08
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多