Execute java file with Runtime.getRuntime().exec()

后端 未结 1 1767
鱼传尺愫
鱼传尺愫 2021-01-26 11:40

This code will execute an external exe application.

private void clientDataActionPerformed(java.awt.event.ActionEvent evt) {                                              


        
相关标签:
1条回答
  • 2021-01-26 11:45

    First, you command line looks wrong. A execution command is not like a batch file, it won't execute a series of commands, but will execute a single command.

    From the looks of things, you are trying to change the working directory of the command to be executed. A simpler solution would be to use ProcessBuilder, which will allow you to specify the starting directory for the given command...

    For example...

    try {
        ProcessBuilder pb = new ProcessBuilder("java.exe", "testfile");
        pb.directory(new File("C:\Users\sg552\Desktop"));
        pb.redirectError();
        Process p = pb.start();
        InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
        consumer.start();
        p.waitFor();
        consumer.join();
    } catch (IOException | InterruptedException ex) {
        ex.printStackTrace();
    }
    
    //...
    
    public class InputStreamConsumer extends Thread {
    
        private InputStream is;
        private IOException exp;
    
        public InputStreamConsumer(InputStream is) {
            this.is = is;
        }
    
        @Override
        public void run() {
            int in = -1;
            try {
                while ((in = is.read()) != -1) {
                    System.out.println((char)in);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                exp = ex;
            }
        }
    
        public IOException getException() {
            return exp;
        }
    }
    

    ProcessBuilder also makes it easier to deal with commands that might contain spaces in them, without all the messing about with escaping the quotes...

    0 讨论(0)
提交回复
热议问题