3

I am busy creating a GUI in Java with buttons such that if I press a button it must open another program like Excel or Word and also a folder. Is there anyway that this is possible?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Jason Samuels
  • 951
  • 6
  • 22
  • 40

2 Answers2

6

You would do something like this...

if (Desktop.isDesktopSupported()) {
       Desktop.getDesktop().open(new File("c:\\a.doc"));
}

If they have word then this file will open in word.

0

Try the below code. Replace the string notepad with your program name with it's path. To open a folder use "explorer c:\\z" in the place of notepad string to open folder z for Windows OS. Use "nautilus /directory" to open directory for Linux OS.

try{
        java.lang.Runtime.getRuntime().exec("notepad");
        }
        catch(Exception e){
            System.err.println(e.getMessage());
        }
  • 2
    Please read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html) in any example using `exec`. Then ignore that it refers to `exec` and build the `Process` using a `ProcessBuilder`. Also break a `String arg` into `String[] args` to account for arguments which themselves contain spaces. `Desktop.open(File)` is a better path for this functionality, but using a `Process` will work if it is not inherently ..fragile (as in the above example). – Andrew Thompson Aug 11 '13 at 17:32