0

I am trying to execute a java compiled file from another java program, and I am having some issues.

When I run from my terminal the command java -cp ".:lib/MyLib.jar" javaFiles/g1/MyCompiledProgram I can execute MyCompiledProgram without any issue.

But when I try to execute the same command from code using the following method:

Process process = Runtime.getRuntime().exec(String.format("java -cp  \".:%s\" javaFiles/g1/MyCompiledProgram",Path.of(PATH_MYLIB)));
String error = null;
process.waitFor();
if(process.exitValue() != 0){
    try(Scanner scanner = new Scanner(process.getErrorStream())){
        error = scanner.useDelimiter("\\A").next();
    }
    System.out.println(error);
}

I get a ClassNotFoundException error. I checked that the directory java was using to execute the command was correct (running the pwd command) and it is the correct one.

Does anyone has any idea why is not finding the class? Thanks :)

  • Really? The command works when run directly? That's weird, given that `javaFiles/g1/MyCompiledProgram` is not a class name. `javaFiles.g1.MyCompiledProgram` would be, if the `MyCompiledProgram.java` file started with `package javaFiles.g1;`, but that sounds unlikely. – Andreas Feb 07 '21 at 12:19
  • Perhaps reading through the answer to [What does “Could not find or load main class” mean?](https://stackoverflow.com/q/18093928/5221149) might allow you to figure out what you're doing wrong. – Andreas Feb 07 '21 at 12:21
  • I think the real problem is that `exec` doesn't understand shell quoting. So those quote characters will be seen by the `java` command and it won't understand them. – Stephen C Feb 07 '21 at 12:22
  • @Andreas thanks for the link, really useful information and yes, the command works when run directly, I am using Fedora System with a Fish terminal. – Antonio Ramírez Soláns Feb 07 '21 at 14:15
  • @StephenC I see, and how can I fix it? Is there any other method to execute .class files from other java source code? – Antonio Ramírez Soláns Feb 07 '21 at 14:16
  • Yea sure. See https://stackoverflow.com/questions/161859/using-quotes-within-getruntime-exec. – Stephen C Feb 07 '21 at 14:51
  • The Java class name *should* be given with `.`, not `/`, as separators. --- If you're on Windows, the path-separator *must* be `;`, not `:`. You can use `System.getProperty("path.separator")` to get the correct character for the platform you're on. – Andreas Feb 07 '21 at 16:50

0 Answers0