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

六眼飞鱼酱① 提交于 2019-12-02 09:47:57

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!