Njunwa Wamavoko Njunwa Wamavoko - 5 days ago 5
Java Question

How Can I execute external program with arguments in Java

I want to launch external Program with Arguments(one of the argument is to load the Config file to that external program) after I click the button of javafx app(the btn event not included in the code) but I wonder why it keeps giving me errors!

My IDE is InjellJ IDEA Community edition

I know this question is the duplicate but among all the examples given here in this platform have been tried with no sucess however my code contains config file as part of the argumets

Here is the code

private String appDomain = Paths.get("").toAbsolutePath().normalize().toString();
private String exepath = appDomain+"\\src\\bin\\exeResources\\MyExe.exe";
private String exeargs = appDomain+"\\src\\bin\\exeResources\\MyExe.ppx silent-load";

try {
Runtime r = Runtime.getRuntime();
r.exec(exepath +" "+exeargs);
} catch (IOException e) {

e.printStackTrace();
}


when I remove the "exeargs" I get the error
CreateProcess error=193, %1 is not a valid Win32 application

Making it difficult for me to know if "exeargs" can work with the above snippet.

Your help will be appreciated

EDIT

The exefile and execonfig I have to load is located in one of the package in my project
**bin.exeResource**

Printing the paths and args by

System.out.println(exepath+" "+exeargs);


Gives me

C:\Users\{MyUser}\OneDrive\IntelliJ IDEA Projects\MyProject Package\src\bin\exeResources\MyExe.exe ...\src\bin\exeResources\MyExe.ppx silent-load


with an Error

CreateProcess error=193, %1 is not a valid Win32 application

Answer

There is a exec method specifically overloaded for your purposes. It takes as an argument String array which holds the command and the arguments for the command. That seems to be exactly what you need. Please look at the API

Comments