¿Alguien puede indicarme la dirección correcta sobre cómo abrir el navegador web predeterminado y configurar la página en "www.example.com" gracias
¿Alguien puede indicarme la dirección correcta sobre cómo abrir el navegador web predeterminado y configurar la página en "www.example.com" gracias
Respuestas:
java.awt.Desktop
es la clase que estás buscando.
import java.awt.Desktop;
import java.net.URI;
// ...
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("http://www.example.com"));
}
Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)
cheque en su lugar.
Aquí está mi código. Se abrirá la URL dada en el navegador predeterminado (solución multiplataforma).
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Browser {
public static void main(String[] args) {
String url = "http://www.google.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Para mí, la solución Desktop.isDesktopSupported()
no funciona ( Windows 7 y Ubuntu ). Intente esto para abrir el navegador desde el código java:
Ventanas:
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("rundll32 url.dll,FileProtocolHandler " + url);
Mac
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("open " + url);
Linux:
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
String[] browsers = { "epiphany", "firefox", "mozilla", "konqueror",
"netscape", "opera", "links", "lynx" };
StringBuffer cmd = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
if(i == 0)
cmd.append(String.format( "%s \"%s\"", browsers[i], url));
else
cmd.append(String.format(" || %s \"%s\"", browsers[i], url));
// If the first didn't work, try the next browser and so on
rt.exec(new String[] { "sh", "-c", cmd.toString() });
Si desea tener una aplicación multiplataforma, debe agregar la verificación del sistema operativo (por ejemplo):
String os = System.getProperty("os.name").toLowerCase();
Ventanas:
os.indexOf("win") >= 0
Mac:
os.indexOf("mac") >= 0
Linux:
os.indexOf("nix") >=0 || os.indexOf("nux") >=0
xdg-open
es mucho mejor en este caso. Por lo tanto, la solución podría ser tan simple como la de macOS.
También puede usar Runtime para crear una solución multiplataforma:
import java.awt.Desktop;
import java.net.URI;
public class App {
public static void main(String[] args) throws Exception {
String url = "http://stackoverflow.com";
if (Desktop.isDesktopSupported()) {
// Windows
Desktop.getDesktop().browse(new URI(url));
} else {
// Ubuntu
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
}
}
}
Como se indica en la respuesta proporcionada por Tim Cooper, java.awt.Desktop
ha proporcionado esta capacidad desde la versión 6 de Java (1.6), pero con la siguiente advertencia:
Para las plataformas que no son compatibles o no proporcionan java.awt.Desktop
, consulte el proyecto BrowserLauncher2 . Se deriva y algo actualizado de la clase BrowserLauncher originalmente escrita y publicada por Eric Albert. Utilicé la clase BrowserLauncher original con éxito en una aplicación Java multiplataforma que se ejecutaba localmente con una interfaz de navegador web a principios de la década de 2000.
Tenga en cuenta que BrowserLauncher2 tiene la licencia GNU Lesser General Public License . Si esa licencia es inaceptable, busque una copia del BrowserLauncher original que tiene una licencia muy liberal:
Este código tiene Copyright 1999-2001 de Eric Albert (ejalbert@cs.stanford.edu) y puede redistribuirse o modificarse de cualquier forma sin restricciones, siempre que no se elimine la parte de este comentario desde este párrafo hasta el final del comentario. . El autor solicita que se le notifique de cualquier aplicación, subprograma u otro binario que haga uso de este código, pero eso es más por curiosidad que por cualquier otra cosa y no es obligatorio. Este software no incluye garantía. El autor no es responsable de ninguna pérdida de datos o funcionalidad o de cualquier efecto adverso o inesperado del uso de este software.
Créditos: Steven Spencer, revista JavaWorld (Consejo 66 de Java) Gracias también a Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich y Ron Rabakukk
Es posible que otros proyectos distintos a BrowserLauncher2 también hayan actualizado el BrowserLauncher original para tener en cuenta los cambios en la configuración de seguridad predeterminada del navegador y del sistema desde 2001.
Es muy simple, simplemente escriba el código a continuación:
String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
o si no desea cargar la URL, simplemente escriba el nombre de su navegador en valores de cadena como,
String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
abrirá el navegador automáticamente con la URL vacía después de ejecutar un programa
en Windows, invoque "cmd / k start http://www.example.com " De hecho, siempre puede invocar programas "predeterminados" utilizando el comando de inicio. Por ejemplo, start abc.mp3 invocará el reproductor mp3 predeterminado y cargará el archivo mp3 solicitado.
Espero que no le importe, pero improvisé todas las cosas útiles, desde arriba, y se me ocurrió una clase completa lista para probar ...
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class MultiBrowPop {
public static void main(String[] args) {
OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");
String url = "http://www.birdfolk.co.uk/cricmob";
OUT("We're going to this page: "+ url);
String myOS = System.getProperty("os.name").toLowerCase();
OUT("(Your operating system is: "+ myOS +")\n");
try {
if(Desktop.isDesktopSupported()) { // Probably Windows
OUT(" -- Going with Desktop.browse ...");
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
} else { // Definitely Non-windows
Runtime runtime = Runtime.getRuntime();
if(myOS.contains("mac")) { // Apples
OUT(" -- Going on Apple with 'open'...");
runtime.exec("open " + url);
}
else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours
OUT(" -- Going on Linux with 'xdg-open'...");
runtime.exec("xdg-open " + url);
}
else
OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
}
OUT("\nThings have finished.\nI hope you're OK.");
}
catch(IOException | URISyntaxException eek) {
OUT("**Stuff wrongly: "+ eek.getMessage());
}
}
private static void OUT(String str) {
System.out.println(str);
}
}
Me refundición Brajesh Kumar respuesta 's arriba en Clojure de la siguiente manera:
(defn open-browser
"Open a new browser (window or tab) viewing the document at this `uri`."
[uri]
(if (java.awt.Desktop/isDesktopSupported)
(let [desktop (java.awt.Desktop/getDesktop)]
(.browse desktop (java.net.URI. uri)))
(let [rt (java.lang.Runtime/getRuntime)]
(.exec rt (str "xdg-open " uri)))))
en caso de que sea útil para alguien.