使用Java中的exec进行编译和执行无法使用命令行中的命令

时间:2015-03-10 02:11:09

标签: java shell file-io exec

所以这个想法就是下面代码中的这一行

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

应该与此行做同样的事情

cd /Users/fnord/Documents/workspace/LearningJava/src/PackA/; javac classA.java; cd ..; java PackA.classA

从终端运行第二行时。那就是编译并运行java代码。我误解了exec()的工作原理吗?如果是这样,那么最好的方法是完成我想要完成的任务?

package PackA;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;


public class classA {
    public static void main(String[] args) throws Exception{
        ClassLoader loader = classA.class.getClassLoader();

        //Sets the file path to the path of the current .java file
        File file = new File(loader.getResource(classA.class.getPackage().getName()+"/"+classA.class.getSimpleName()+".class").toString().replaceAll("file:", "").replaceAll("bin", "src").replaceAll("sA.class", "sA.java"));

        BufferedReader in = new BufferedReader(new FileReader(file)); //establishes the reader that will be used to read this .java file    
        StringBuffer string = new StringBuffer(); //the stringBuffer that will be used to hold the contents of this .java file
        String stringRead = in.readLine(); //sets a string to the first line of this .java file

        while((stringRead) != null){ //as long as we haven't reached the end of the file
            string.append(stringRead); //append the line
            string.append(System.getProperty("line.separator")); //go to the next line
            stringRead = in.readLine(); //read the next line
        }

        Integer intToFind = new Integer(0); //the integer being looked for

        if (intToFind<=10) { //as long as the intToFind is less than or equal to 10
            //increment the intToFind in the stringBuffer 
            StringBuffer newProgram = new StringBuffer(string.toString().replaceFirst("[(]"+intToFind.toString(), "("+String.valueOf(++intToFind)));
            //establishes the writer that will be used to write to the file
            BufferedWriter out = new BufferedWriter(new FileWriter(file));

            out.write(newProgram.toString()); //write the newProgram to this .java file with the incremented intToFind

            in.close(); //close both the reader and writer
            out.close();

            //Go to the directory of the java file, compile the code, move down one directory, execute the .class file
            Runtime.getRuntime().exec("cd /Users/fnord/Documents/workspace/LearningJava/src/PackA/; javac classA.java; cd ..; java PackA.classA");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

cd不是程序,它是一个shell命令。

您可以使用ProcessBuilder代替,这将允许您定义应从中执行命令的工作目录上下文

this for example

这样的东西

上一个示例中的违反代码,已更新以提供指定工作目录的功能

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;
    }
}

你可以使用类似的东西打电话......

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

现在,如果您非常勇敢,可以查看How do you dynamically compile and load external java classes?,它使用javax.tools.JavaCompiler`类来编译Java文件......