1

我正在开发我的第一个 java 项目,即一个 TextEditor,它也可以编译和运行文件。编译器 (javax.tools.JavaCompiler) 工作正常,但是当我尝试运行“.class”文件时,什么也没有出现。我需要帮助。

以下是编译代码:

public void compileIt(String s)     //s is the absolute path of file to be compiled
    {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        MyDiagnosticListener listener = new MyDiagnosticListener();
             StandardJavaFileManager fileManager =
                compiler.getStandardFileManager(listener, null, null);

        File file;
        file = new File(s);
         String classOutputFolder ="E:\\codefiles";  //destination for storing .class files

        Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(file);
        Iterable options = Arrays.asList("-d", classOutputFolder);
        JavaCompiler.CompilationTask task =
                compiler.getTask(null, fileManager, listener, options, null, javaFileObjects);
        if (task.call()) {
            System.out.println("compilation done");
        }
        try {
            fileManager.close();
        } catch (IOException ex) {
            Logger.getLogger(getName()).log(Level.SEVERE, null, ex);
        }
    }

运行 .class 文件的代码:

void runIt()
{
  String s = null;

        try {


            // using the Runtime exec method:
            Process p = Runtime.getRuntime().exec("java -cp E:\\codefiles");

            BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));

            // read the output from the command

            while ((s = stdInput.readLine()) != null) {
                System.out.println("output is working:\n");
                System.out.println(s);
            }

            // read any errors from the attempted command
           while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }


        }
        catch (IOException ex1) {
            ex1.printStackTrace();

        }
}
4

1 回答 1

0

一个原因

 Process p = Runtime.getRuntime().exec("java -cp E:\\codefiles");

不起作用是命令行语法错误。您还需要提供一个类名;例如

 Process p = Runtime.getRuntime().exec(
        "java -cp E:\\codefiles  com.example.MyMain");

这假定您尝试运行的类具有合适的main方法。

于 2020-05-02T14:27:16.563 回答