-2

I want to find out how to open any exe in Windows using Java code. I have searched Google before and they only show me part of the code that they use, I think, because it doesn't seem to compile.

I have downloaded JDK 7 to compile. I don't use Eclipse at the moment and also explaining what I had to do to get it to work in detail would help a lot.

to what Sri Harsha Chilakapati said: would i need to create a class for the code?

Thanks to those who answered but i didn't quite get what you meant but i did however manage to find a website which had what i was after: http://www.rgagnon.com/javadetails/java-0014.html

public class Test {
  public static void main(String[] args) throws Exception {
    Process p = Runtime.getRuntime().exec(
    "\"c:/program files/windows/notepad.exe\"");
p.waitFor();
  } 
}

the above was what i was after but thanks again anyway to the people who answered.

2 Answers2

6

Try this.

String myExe = "C:\\MyExe.exe";
String args  = "";

Runtime.getRuntime().exec(myExe + " " + args);

Hope this helps.

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91
  • 3
    There are better (more robust to spaces, say) ways to pass args than just concatenating `args` to `myExe`. See the other `exec` methods in `Runtime`. – Keith Randall Sep 15 '12 at 01:54
  • 4
    Better yet, `"C:/MyExe.exe"`. The "\\" path separator is for Windows. However, "/" works in all operating systems. – JRunner Sep 15 '12 at 01:55
  • 2
    Myself, I'd use a [ProcessBuilder](http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html). – Hovercraft Full Of Eels Sep 15 '12 at 01:56
  • 1
    See http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#pathSeparator for path separator. You can have the right one for your platform without any assumptions. – steffan Sep 15 '12 at 02:02
  • @user1168261 He said perfectly that it's windows and hence there's no need for your path separator – Sri Harsha Chilakapati Sep 15 '12 at 02:03
  • @ Sri Harsha Chilakapati Thats true, but JRunner suggested "/" because it works on all platforms. I just wanted to point out that there is the pathSepartor for all platforms. – steffan Sep 15 '12 at 02:05
  • @SriHarshaChilakapati and the OP's next question will be 'why doesn't this work platform X". Despite what the OP said, user1168261's comment is the correct method for approaching this kind of problem, IMHO - personally, I'd use File.seperator, but that's me – MadProgrammer Sep 15 '12 at 02:40
5

I would recommend the ProcessBuilder, especially for additional arguments.

steffan
  • 619
  • 1
  • 9
  • 18
  • 1
    ProcessBuilder is a better approach than runtime, but you really need to flesh this out with an example so that it is useful to someone with this question. Because they're asking this question it's a safe bet they're not already familiar with process builder. – EdC Sep 15 '12 at 02:24