How do I execute Windows commands in Java?

前端 未结 5 1684
遇见更好的自我
遇见更好的自我 2020-11-29 10:09

I\'m working on a project, and it will give you a list of Windows commands. When you select one, it will perform that command. However, I don\'t know how to do that. I was g

5条回答
  •  醉话见心
    2020-11-29 10:28

    Take advantage of the ProcessBuilder.

    It makes it easier to build the process parameters and takes care of issues with having spaces in commands automatically...

    public class TestProcessBuilder {
    
        public static void main(String[] args) {
    
            try {
                ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "dir");
                pb.redirectError();
                Process p = pb.start();
                InputStreamConsumer isc = new InputStreamConsumer(p.getInputStream());
                isc.start();
                int exitCode = p.waitFor();
    
                isc.join();
                System.out.println("Process terminated with " + exitCode);
            } catch (IOException | InterruptedException exp) {
                exp.printStackTrace();
            }
    
        }
    
        public static class InputStreamConsumer extends Thread {
    
            private InputStream is;
    
            public InputStreamConsumer(InputStream is) {
                this.is = is;
            }
    
            @Override
            public void run() {
    
                try {
                    int value = -1;
                    while ((value = is.read()) != -1) {
                        System.out.print((char)value);
                    }
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
    
            }
    
        }
    }
    

    I'd generally build a all purpose class, which you could pass in the "command" (such as "dir") and it's parameters, that would append the call out to the OS automatically. I would also included the ability to get the output, probably via a listener callback interface and even input, if the command allowed input...

提交回复
热议问题