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

前端 未结 27 1108
误落风尘
误落风尘 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:30

    [At the request of Alexman and dreeves -- see comments --, you will find at this DZones Java Snippet page a full version Os-independent for making, in this instance, a 'ls'. This is a direct answer to their code-challenge.
    What follows below is just the core: Runtime.exec, plus 2 thread to listen to stdout and stderr. ]

    Java "Simple!":

    E:\classes\com\javaworld\jpitfalls\article2>java GoodWindowsExec "dir *.java"
    Executing cmd.exe /C dir *.java
    ...
    

    Or in java code

    String output = GoodWindowsExec.execute("dir");
    

    But to do that, you need to code...
    ... this is embarrassing.

    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
    {
        InputStream is;
        String type;
        StringBuffer output = new StringBuffer();
    
        StreamGobbler(InputStream is, String type)
        {
            this.is = is;
            this.type = type;
        }
    
        public void run()
        {
            try
            {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    System.out.println(type + ">" + line);
                    output.append(line+"\r\n")
                } catch (IOException ioe)
                  {
                    ioe.printStackTrace();  
                  }
        }
        public String getOutput()
        {
            return this.output.toString();
        }
    }
    public class GoodWindowsExec
    {
        public static void main(String args[])
        {
            if (args.length < 1)
            {
                System.out.println("USAGE: java GoodWindowsExec ");
                System.exit(1);
            }
        }
        public static String execute(String aCommand)
        {
            String output = "";
            try
            {            
                String osName = System.getProperty("os.name" );
                String[] cmd = new String[3];
                if( osName.equals( "Windows 95" ) )
                {
                    cmd[0] = "command.com" ;
                    cmd[1] = "/C" ;
                    cmd[2] = aCommand;
                }
                else if( osName.startsWith( "Windows" ) )
                {
                    cmd[0] = "cmd.exe" ;
                    cmd[1] = "/C" ;
                    cmd[2] = aCommand;
                }
    
                Runtime rt = Runtime.getRuntime();
                System.out.println("Executing " + cmd[0] + " " + cmd[1] 
                                   + " " + cmd[2]);
                Process proc = rt.exec(cmd);
                // any error message?
                StreamGobbler errorGobbler = new 
                    StreamGobbler(proc.getErrorStream(), "ERROR");            
    
                // any output?
                StreamGobbler outputGobbler = new 
                    StreamGobbler(proc.getInputStream(), "OUTPUT");
    
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
    
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);   
    
                output = outputGobbler.getOutput();
                System.out.println("Final output: " + output);   
    
            } catch (Throwable t)
              {
                t.printStackTrace();
              }
            return output;
        }
    }
    

提交回复
热议问题