LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Opening programs in Java (http://www.linuxquestions.org/questions/programming-9/opening-programs-in-java-337713/)

Diederick 06-27-2005 01:37 PM

Opening programs in Java
 
I want to know if one kan use java to open another program from within your java program, and how or what to use to accomplish this.

Thanx Diederick

ilikejam 06-27-2005 01:49 PM

Hi.

You can indeed:
Code:

runEnviron = Runtime.getRuntime();
try {
    Process burnProcess = runEnviron.exec("/usr/bin/myOtherProgram");
} catch (IOException e) {
    System.out.println("Problem!");
}

Dave

Diederick 06-27-2005 02:21 PM

Thanx but one more problem
 
What is runEnviron? I have never used this before so i'm still new at this.

Thanx

ilikejam 06-27-2005 03:14 PM

Oops. My mistake. I had runEnviron declared at the top of the class.
Code:

private Runtime runEnviron;
runEnviron = Runtime.getRuntime();
try {
    Process burnProcess = runEnviron.exec("/usr/bin/myOtherProgram");
} catch (IOException e) {
    System.out.println("Problem!");
}

Dave

Diederick 06-27-2005 03:20 PM

Almost done.
 
Thanx Dave it's working now!!! The last thing i want to know is how to send the selected file to that new program sothat it opens the file when the program opens. I used a JFile chooser to get the file.

ilikejam 06-27-2005 03:38 PM

OK, something like this should give you the path to the file in 'newSource'

Code:

String newSource = "";
final JFileChooser sourceChooser = new JFileChooser();
int returnValue = sourceChooser.showOpenDialog(caller);
if (returnValue == JFileChooser.APPROVE_OPTION) {
        File sourceFile = sourceChooser.getSelectedFile();
        newSource=sourceFile.getAbsolutePath();
}

'caller' is the JButton which launced the ActionEvent.
Things get a bit interesting after that. If there are any spaces in the file's path, you'll have problems if you just do
Code:

runEnviron.exec("/usr/bin/myOtherProgram" + newSource);
because Java will parse the string according to spaces and pass each chunk of the file path as a separate argument. You should add each argument as a separate string into an array of strings to be sure it'll work with paths with spaces, e.g.
Code:

String[] command = {"/usr/bin/myOtherProgram", newSource};
Process burnProcess = runEnviron.exec(command);

I hope that makes sense. Hit me back if it doesn't.

Also, Sun has some excellent documentation online:
http://java.sun.com/j2se/1.5.0/docs/api/

Dave

Diederick 06-27-2005 03:58 PM

Yes Yes Yes
 
Dave thanx very much i got the file loaded and every thing works.
Thanx 4 your help and time. Hope i could one day be as good as you in java.

Thanx Diederick (SA)


All times are GMT -5. The time now is 10:25 AM.