Reputation: 59
So I've recently wrote code:
Runtime r = Runtime.getRuntime();
Process p = null;
try
{
p = r.exec("firefox");
p.waitFor();
} catch (Exception e)
{
System.out.println("Error executing app");
}
And I was wondering if there is a way to for example force the browser not just to open but execute certain commands or just open a link. How do I do that?
Upvotes: 1
Views: 437
Reputation: 3350
If you want to open the default browser with an URL provided you can use this function. java.awt.Desktop
is suitable for windows and xdg-open
opens a file or URL in the user's preferred application in linux environment. If a URL is provided the URL will be opened in the default web browser.
public void openDefaultBrowser(URI uri) throws BrowserException {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
// windows
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (IOException e) {
throw new BrowserException(e.getLocalizedMessage());
}
} else {
// linux / mac
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + uri.toString());
} catch (IOException e) {
throw new BrowserException(e.getLocalizedMessage());
}
}
}
Upvotes: 1