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 :)

7
  • 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. Commented Feb 7, 2021 at 12:19
  • Perhaps reading through the answer to What does “Could not find or load main class” mean? might allow you to figure out what you're doing wrong. Commented Feb 7, 2021 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. Commented Feb 7, 2021 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. Commented Feb 7, 2021 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? Commented Feb 7, 2021 at 14:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.