Sithik SweetRascal
Sithik SweetRascal

Reputation: 91

Runtime exec launch application in background java

when I run the following code, the notepad is getting launched in background instead of foreground

Runtime rt = Runtime.getRuntime();
try {
    rt.exec("notepad.exe");
} catch (IOException ex) {
}

Example:

From my java desktop application, I am trying to launch "notepad.exe". The notepad is getting launched behind the application.

I would like to see that notepad should appear in foreground.

Could you please help me to resolve it?

Upvotes: 2

Views: 1635

Answers (1)

Benjamin Albert
Benjamin Albert

Reputation: 748

The following will open both files and executables (.exe):

Java 1.6 and above:

try {
   Desktop.getDesktop().open(new File("notepad.exe"));
} catch (Exception e) {
   e.printStackTrace();
}

Java 1.5 and under, without external library (windows only):

try {
   Runtime.getRuntime().exec("cmd /c \"notepad.exe\"");
} catch (Exception e) {
   e.printStackTrace();
}

I only tested the 1.5 solution with opening excel files but not with opening executable files, but I'm guessing it could work to.

Upvotes: 1

Related Questions