Reputation: 513
Im writing an application. There the app has to open firefox when certain req are met. I did a small research. All i can find is the following code.
Runtime rt = null;
rt = Runtime.getRuntime();
try {
rt.exec("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe google.com");
} catch (IOException e) {
e.printStackTrace();
}
What i want to know is that is that any method to open a specific application without giving the path because all users wont install the application in same path. So like searching with the name only. Please help. Thanks in advance.
Upvotes: 0
Views: 186
Reputation: 3281
It's actually quite complex, you can use feature provided by nio
package in Java 7:
The new java.nio.file.Files class provides a factory method, walkFileTree, you can use to traverse a tree of directories and files.
to find out more go directly to the blog I just quoted: https://blogs.oracle.com/thejavatutorials/entry/traversing_a_file_tree_in
Upvotes: 1
Reputation: 115328
Searching of executable in path is the responsibility of shell. This mechanism is invoked when you execute command from command prompt or from OS launcher. To enable this mechanism from java you should run the application through cmd
on Windows or /bin/sh
on Linux.
In your case change your code to
rt.exec("cmd /c chrome.exe google.com")
EDIT
1. this will work whether chrome is the default browser or not.
2. This will NOT work if chrome is not available in system path
(e.g. if it is not installed).
So, then it depends on what do you really want. If you have to show URL in default browser use desktop.browse(uri);
(as it was already mentioned by @Arvind). If however you really want to open specific application (whether it is browser or not) use methods I suggested you.
Upvotes: 1
Reputation: 274
Giving the name of the application and providing an automatic search is really a Herculean task. It has got so many complexities involved:
I would give you a simple suggestion, if you are developing a GUI apllication, allow the user to give the path and set a button ("Set Default Path") and allow user to click on. So, the default path will be stored in a string variable and you can call it from the `exec()`
Upvotes: 1
Reputation:
You may use the Desktop
class, find more in detail doc here
URI uri = null;
try {
uri = new URI("http://www.google.com");
desktop.browse(uri);
} catch(IOException ioe) {
System.out.println("The system cannot find the " + uri +
" file specified");
//ioe.printStackTrace();
} catch(URISyntaxException use) {
System.out.println("Illegal character in path");
//use.printStackTrace();
}
Upvotes: 4