Compiling and executing using exec in Java fails using command that works from the command line

后端 未结 1 647
被撕碎了的回忆
被撕碎了的回忆 2020-12-22 11:03

So the idea is that this line in the code below

Runtime.getRuntime().exec(\"cd /Users/fnord/Documents/workspace/LearningJava/src/PackA/; javac classA.java; c         


        
相关标签:
1条回答
  • 2020-12-22 11:40

    cd is not a program, it's a shell command.

    You could use ProcessBuilder instead, which would allow you to define the working directory context from which the command should be executed

    Something like this for example

    Abbriviated code from previous example, updated to provide the ability to specifiy the working directory

    public int compile(String file, File workingDirectory) throws IOException, InterruptedException {        
        ProcessBuilder pb = new ProcessBuilder("javac", file);
        pb.redirectError();
        pb.directory(new File(workingDirectory));
        Process p = pb.start();
        InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
        consumer.start();
    
        int result = p.waitFor();
    
        consumer.join();
    
        System.out.println(consumer.getOutput());
    
        return result;        
    }
    
    public class InputStreamConsumer extends Thread {
    
        private InputStream is;
        private IOException exp;
        private StringBuilder output;
    
        public InputStreamConsumer(InputStream is) {
            this.is = is;
        }
    
        @Override
        public void run() {
            int in = -1;
            output = new StringBuilder(64);
            try {
                while ((in = is.read()) != -1) {
                    output.append((char) in);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                exp = ex;
            }
        }
    
        public StringBuilder getOutput() {
            return output;
        }
    
        public IOException getException() {
            return exp;
        }
    }
    

    Which you could call using something like...

    compile("PackA/classA.java", new File("/Users/fnord/Documents/workspace/LearningJava/src"));
    

    Now, if you're really courageous, you could take a look at How do you dynamically compile and load external java classes?, which uses javax.tools.JavaCompiler` class to compile a Java file...

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