Java Runtime.getRuntime(): getting output from executing a command line program

前端 未结 12 1677
清歌不尽
清歌不尽 2020-11-22 00:18

I\'m using the runtime to run command prompt commands from my Java program. However, I\'m not aware of how I can get the output the command returns.

Here is my code:

12条回答
  •  感动是毒
    2020-11-22 00:48

    Pretty much the same as other snippets on this page but just organizing things up over an function, here we go...

    String str=shell_exec("ls -l");
    

    The Class function:

    public String shell_exec(String cmd)
           {
           String o=null;
           try
             {
             Process p=Runtime.getRuntime().exec(cmd);
             BufferedReader b=new BufferedReader(new InputStreamReader(p.getInputStream()));
             String r;
             while((r=b.readLine())!=null)o+=r;
             }catch(Exception e){o="error";}
           return o;
           }
    

提交回复
热议问题