-1

I have this code:

import javax.swing.JOptionPane;

class OpenProgram {

    public static void main(String[] args) throws Exception {

        // opens the JOptionPane
        String path = JOptionPane
                .showInputDialog("Type the path to a program or other file(forward slashes)");

        //runs the program
        Process run = Runtime.getRuntime().exec("\"" + path);
        System.out.println("Program Opened!");
        run.waitFor();
    }
}

It is supposed to bring up a JOptionPane and have the user type in the path to a program, then run the specified program, but when I test it and press OK on the JOptionPane, it says it couldn't run it. Any help?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
livefree75
  • 720
  • 8
  • 18
  • *it says it couldn't run it* what exactly? some file not found exception? – kajacx Jul 02 '13 at 21:17
  • Why do you do `"\"" + path`? – Jim Garrison Jul 02 '13 at 21:18
  • What exactly you want to execute? There are many thing we can wonder about. – Smit Jul 02 '13 at 21:19
  • are you going to run something like ipconfig? notepad?, so you need to locate the win directory by WinDir os variable, and then call the os exe file –  Jul 02 '13 at 22:20
  • Read (and implement) *all* the recommendations of [When Runtime.exec() won't](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html). That might solve the problem. If not, it should provide more information as to the reason it failed. 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. – Andrew Thompson Jul 03 '13 at 00:10
  • *"`.showInputDialog("Type the path to a program`"* That is cruel! Offer the user a `JFileChooser`.. – Andrew Thompson Jul 03 '13 at 00:11

3 Answers3

1

Well, expect the java.io.IOException, make sure the path is correct, and sometimes accessing to the file is denied, or the program you are trying to open is not a valid Win32 application.

Try to use Desktop.getDesktop().open(new File(path)).

Azad
  • 5,047
  • 20
  • 38
0

Is it possible that the runtime is not able to find the executable that you want to run? Are you using Windows or Linux or Mac? The folder where the executable is present may not be in the path or maybe it is unable to find a dynamically linked library needed by your program. Can you paste the value contained in the variable path? Also when you say "it couldn't run it", do you see any exception?

0

If you are not seeing any exception, then your path is probably not linked or correct. Please give more info if possible so answering is easier. You gave a really vague post.

Foris Kuang
  • 115
  • 1
  • 9