Search code examples
javacmdenvironment-variablesjava-homejava-17

Execute "java -jar" from another JAR but using different java versions xD


My project is made using JDK 17. From this JAR I need to exec another JAR (by a cmd command). The problem is that for the second JAR I need JRE < 1.8 I've tried with Runtime.getRuntime().exec(cmd); and with ProcessBuilder but I can't make it work. CMD command used is below. I've tried to temporarily set JAVA_HOME to 1.6 but I guess cmd.exe takes the java used by the Parent JAR. The second JAR is not made by me and I can't edit it ... so I need to use <1.8 for it.

String cmd = "set JAVA_HOME="C:\ExtensieImpoziteYCS\duk\jre6\bin" & java -jar "duk/DUKIntegrator.jar" -s P2000 "duk/P2000.xml" "duk/P2000-err.txt" 0 0 $ $ aladdin 5";
Process duk = Runtime.getRuntime().exec(cmd);
duk.waitFor();
duk.destroy();
ProcessBuilder processBuilder = new ProcessBuilder();
        try {
            Map<String, String> env = processBuilder.environment();
            env.put("JAVA_HOME", "C:\\ExtensieImpoziteYCS\\duk\\jre6\\bin\"");
            processBuilder.command("cmd.exe", "/c", cmd);
            Process process = processBuilder.start();

            StringBuilder output = new StringBuilder();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }

            int exitVal = process.waitFor();
            if (exitVal == 0) {
                System.out.println("Success!");
                System.out.println(output);
                System.exit(0);
            } else {
                System.out.println(output);
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

The second JAR is used to digitally sign a PDF and because of the old JRE used for it, on the new JDK I get this error:

java.lang.IllegalAccessException: class pdf.Sign cannot access class sun.security.mscapi.SunMSCAPI (in module jdk.crypto.mscapi) because module jdk.crypto.mscapi does not export sun.security.mscapi to unnamed module @16022d9d

Using JRE 1.6 directly from CMD works perfectly...


Solution

  • Damn I'm stupid. I just needed to use another java.exe than "java -jar"

    The solution is:

    .\\duk\\jre6\\bin\\java.exe -jar \"duk/DUKIntegrator.jar\" -s