2016-06-24 80 views
1

我想让一个应用程序,将允许我在Android中发出命令,并给我结果。这似乎工作正常,但有一些例外,即等待一段时间以获得更多输出的命令未得到正确处理。我试图发出命令“su & & nmap -sS 192.168.1.1”,我得到的所有输出是nmap已经启动。有谁知道一种方法,不仅可以获得nmap已经启动的输出,还可以使用下面代码的修改版本进行扫描的结果。Android java InputStreamReader

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

可能'su'只是在等待密码吗? –

+0

您需要关闭输入到输入流的输出流。 – EJP

回答

-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(); 
    } 
} 
+2

毫无意义。一旦'readLine()'返回null,就是这样。你可以从现在起睡到世界末日,但永远不会有更多的输入。 – EJP

+0

必须有一种方法来获得输出,对吗?我可能一直在用错误的方式去解决它? – Fuion

相关问题