Using CMD as a Process

后端 未结 6 1633
無奈伤痛
無奈伤痛 2020-12-22 09:38

I\'m trying to run commands straight through the CMD on Windows (Terminal on Linux). I have the following code. It\'s acting very strangely. First, when run the program does

6条回答
  •  生来不讨喜
    2020-12-22 10:02

    I found this code on the net years ago. I cant remember where. It's pretty old so there might be something better out there now.

     private void executeCommand(String cmd) {
            try {
                Runtime rt = Runtime.getRuntime();
    
                Process proc = rt.exec(cmd);
    
                // any error message?
                StreamHandler errorGobbler = new StreamHandler(proc.getErrorStream(), "ERR");
    
                // any output?
                StreamHandler outputGobbler = new StreamHandler(proc.getInputStream(), "OUT");
    
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
    
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    
        }
    

    And the class:

    import java.util.*;
    import java.io.*;
    
    public class StreamHandler extends Thread {
        InputStream is;
        String type;
        OutputStream os;
    
        StringBuffer output;
    
        StreamHandler(InputStream is, String type) {
            this(is, type, null);
        }
    
        StreamHandler(InputStream is, String type, OutputStream redirect) {
    
            this.is = is;
            this.type = type;
            this.os = redirect;
            output = new StringBuffer(100);
        }
    
        public void run() {
            try {
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
    
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null) {
                    if (pw != null)
                        pw.println(line);
                    System.out.println(type + ">" + line);
                }
                if (pw != null)
                    pw.flush();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
    

提交回复
热议问题