System() function in java project

Asked By 240 points N/A Posted on -
qa-featured

Hi,

I am a student of CSE. I am currently beginning to program with java using netbeans. I know some C++. I am now doing a project where I have to call some other program, from within the java program. I know there is a function in C/C++ called system("program.exe"), which can call an external exe. I have used it too. Is there any way I can do something in java?

SHARE
Best Answer by shababhsiddique
Answered By 0 points N/A #91546

System() function in java project

qa-featured

You have to – declare a Runtime object and assign it the current runtime – Create a process using the runtime object.exec("the address of your exe") – wait for the process to be exited Here is a small function in java to help you get started. public int runProgram() { int ret = -1; try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("cmd.exe /c a.exe"); proc.waitFor(); ret = proc.exitValue(); } catch (Throwable t) { t.printStackTrace(); return ret; } return ret; }

Answered By 240 points N/A #91548

System() function in java project

qa-featured

Thanks for the reply but the function doesn't seem to work properly. I can see it calling something, but no popups appear.

Answered By 0 points N/A #91549

System() function in java project

qa-featured

Hi KJ,

ProcessBuilding is a more complicated task in Java. There is no simple, single function call like system(). If you use processbuilder like Shababhsiddique said, then you also need to redirect the output and input to a buffered reader/writer and use them parallel with the process. Quite complicating task. Checkout.

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html

And a tutorial here:

https://www.javaworld.com/article/2071275/core-java/when-runtime-exec—won-t.html

Answered By 240 points N/A #91550

System() function in java project

qa-featured

Thanks Apoclypse but the tutorial is out of my limit of understanding. Is there any Simple way. I don't need to manipulate the program inside java just a call would be enough.

Best Answer
Best Answer
Answered By 0 points N/A #91551

System() function in java project

qa-featured

I guess your program is a command line one. Use,  Process proc = rt.exec("cmd.exe  /c   start   yourprogram.exe"); instead of,  Process proc = rt.exec("cmd.exe /c yourprogram.exe"); This shall start a popup cmd screen as you need.

Related Questions