Run a programme by java application
You may have encountered situations where you wish to run a programme say Web Browser (FireFox) from your Java programme.
It is very simple
public static void main(String[] args) {
Desktop dt = Desktop.getDesktop();
try {
try {
dt.browse(new URI("http://yahoo.com"));
} catch (URISyntaxException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
It is very simple
- Find the location of the actual executable of the programme.
- As in the case of FireFox Web Browser, the actual executable file is placed at C:\Program Files\Mozilla Firefox\firefox.exe
- You can use the following code to run it from your Java application
- Runtime runtime = Runtime.getRuntime();
runtime.exec("K:/Program Files/Mozilla Firefox/firefox.exe"); - (YOU MUST USE A TRY CATCH BLOCK. Just excluded them for clarity)
- ENJOY programming :-)
public static void main(String[] args) {
Desktop dt = Desktop.getDesktop();
try {
try {
dt.browse(new URI("http://yahoo.com"));
} catch (URISyntaxException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
Comments
it is better to use File.seperator.
However in this case, it is only intended to work with Windows XP.
(Because the directory structure exists in XP)
But suppose if you are using similar scenario to open a picture placed at ./images/pic.jpg say. Then it's better to use File.seperator as the application would work in both Windows and Linux.
Since Windows and Linux use different slash notations, File.seperator first looks at what the OS is and then replaces the relevant path seperator.
:-)