【问题标题】:I'm having trouble in running the code compiled using javax.tools.JavaCompiler我在运行使用 javax.tools.JavaCompiler 编译的代码时遇到问题
【发布时间】:2020-08-17 00:17:27
【问题描述】:

我正在开发我的第一个 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();

        }
}

【问题讨论】:

    标签: java javacompiler


    【解决方案1】:

    一个原因

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2013-04-25
      • 1970-01-01
      相关资源
      最近更新 更多