Making a system call that returns the stdout output as a string

前端 未结 27 855
误落风尘
误落风尘 2020-11-27 05:13

Perl and PHP do this with backticks. For example,

$output = `ls`;

Returns a directory listing. A similar function, system(\"foo\")

27条回答
  •  有刺的猬
    2020-11-27 05:39

    Granted, it is not the smaller ( from all the languages available ) but it shouldn't be that verbose.

    This version is dirty. Exceptions should be handled, reading may be improved. This is just to show how a java version could start.

    Process p = Runtime.getRuntime().exec( "cmd /c " + command );
    InputStream i = p.getInputStream();
    StringBuilder sb = new StringBuilder();
    for(  int c = 0 ; ( c =  i.read() ) > -1  ; ) {
        sb.append( ( char ) c );
    }
    

    Complete program below.

    import java.io.*;
    
    public class Test { 
        public static void main ( String [] args ) throws IOException { 
            String result = execute( args[0] );
            System.out.println( result );
        }
        private static String execute( String command ) throws IOException  { 
            Process p = Runtime.getRuntime().exec( "cmd /c " + command );
            InputStream i = p.getInputStream();
            StringBuilder sb = new StringBuilder();
            for(  int c = 0 ; ( c =  i.read() ) > -1  ; ) {
                sb.append( ( char ) c );
            }
            i.close();
            return sb.toString();
        }
    }
    

    Sample ouput ( using the type command )

    C:\oreyes\samples\java\readinput>java Test "type hello.txt"
    This is a sample file
    with some
    lines
    

    Sample output ( dir )

     C:\oreyes\samples\java\readinput>java Test "dir"
     El volumen de la unidad C no tiene etiqueta.
     El número de serie del volumen es:
    
     Directorio de C:\oreyes\samples\java\readinput
    
    12/16/2008  05:51 PM              .
    12/16/2008  05:51 PM              ..
    12/16/2008  05:50 PM                42 hello.txt
    12/16/2008  05:38 PM             1,209 Test.class
    12/16/2008  05:47 PM               682 Test.java
                   3 archivos          1,933 bytes
                   2 dirs            840 bytes libres
    

    Try any

    java Test netstat
    java Test tasklist
    java Test "taskkill /pid 416"
    

    EDIT

    I must admit I'm not 100% sure this is the "best" way to do it. Feel free to post references and/or code to show how can it be improved or what's wrong with this.

提交回复
热议问题