【问题标题】:Could not load main class when compiled and executed with Runtime.exec()使用 Runtime.exec() 编译和执行时无法加载主类
【发布时间】:2017-07-06 08:40:08
【问题描述】:

我有以下代码来运行三个执行:

            public static void main(String[] args) throws InterruptedException, IOException 
            {
                String filepath1 = "cmd /c gradlew jmhJar";
                String filepath2 = "cmd /c java -jar path/to/the/file/filename.jar -rf csv -rff path/to/save/file1.csv -wi 3 -i 5 -f 2";
                String filepath4 = "cmd /c javac path/to/the/file/ParserHash.java";/*Code to compile is parserHash.java*/

    String filepath3 = "cmd /c java path/to/the/compiled/class/ParserHash "C:/Users/msek/Desktop/trial/result/file1.csv C:/Users/msek/Desktop/trial/result/file2.csv C:/Users/msek/Desktop/trial/result/file3.csv";
                try
                    {          
                    runProcess(filepath1); 
                    runProcess(filepath2);
                    System.out.println("Sucessfully written into file1.csv");
                    runProcess(filepath4);
                    System.out.println("Compilation Over");
                    runProcess(filepath3);
                    System.out.println("Program Sucessfully Executed");
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }

public static void  runProcess(String processString)
{
    try
    {

     final Process p = Runtime.getRuntime().exec(processString);

        new Thread(new Runnable() {
            public void run() {
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;

                try {
                    while ((line = input.readLine()) != null)
                        System.out.println(line);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        p.waitFor();
    }

    catch (Exception x)
    {
        x.printStackTrace();
    }
}

如果我将 java 文件编译到该特定目录并成功编译并运行它,它就会成功执行。但是如果我像“cmd /c path/to/java/file/file.java”一样传递它,它会被编译但是当我执行它时,我会收到一个错误,指出即使存在类文件也无法找到或加载主类。

我查看了有关此建议构建过程的各种链接,但这不起作用。

我只是想知道我哪里出错了,以及如何编译,通过使用 Runtime.exec() 传递多个参数来执行一个 java 文件..

【问题讨论】:

  • javac 之后,您是否构建了.jar 文件?
  • 为你的命令添加一个类路径
  • @UsagiMiyamoto 实际上前两个进程运行良好,没有任何问题,问题从 javafile 的编译部分开始,即文件路径 3 和文件路径 4 编译执行。

标签: java processbuilder runtime.exec


【解决方案1】:
java path/to/the/compiled/class/ParserHash

如果您在使用 exec() 时遇到问题,您应该:

  1. 自己从命令行尝试该命令。在这种情况下,它会以同样的方式失败。
  2. 查看命令的语法。在这种情况下,您将了解到java 命令的参数不是路径而是类名,完全限定,即包括包名。带点。

【讨论】:

    猜你喜欢
    • 2019-08-18
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2010-12-11
    相关资源
    最近更新 更多