Qualcuno può indicarmi la giusta direzione su come aprire il browser web predefinito e impostare la pagina su "www.example.com" grazie
Qualcuno può indicarmi la giusta direzione su come aprire il browser web predefinito e impostare la pagina su "www.example.com" grazie
Risposte:
java.awt.Desktop
è la classe che stai cercando.
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)
invece il segno di spunta.
Ecco il mio codice. Si aprirà l'URL specificato nel browser predefinito (soluzione multipiattaforma).
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();
}
}
}
}
Per me la soluzione con Desktop.isDesktopSupported()
non funziona ( Windows 7 e Ubuntu ). Prova questo per aprire il browser dal codice java:
Finestre:
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() });
Se vuoi avere un'applicazione multipiattaforma, devi aggiungere il controllo del sistema operativo (ad esempio):
String os = System.getProperty("os.name").toLowerCase();
Finestre:
os.indexOf("win") >= 0
Mac:
os.indexOf("mac") >= 0
Linux:
os.indexOf("nix") >=0 || os.indexOf("nux") >=0
xdg-open
è molto meglio in questo caso. La soluzione potrebbe essere quindi semplice come quella di macOS.
È inoltre possibile utilizzare il runtime per creare una soluzione multipiattaforma:
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);
}
}
}
Come notato nella risposta fornita da Tim Cooper, java.awt.Desktop
ha fornito questa funzionalità dalla versione Java 6 (1.6), ma con il seguente avvertimento:
Per le piattaforme che non supportano o forniscono java.awt.Desktop
, guarda nel progetto BrowserLauncher2 . È derivato e in qualche modo aggiornato dalla classe BrowserLauncher originariamente scritta e rilasciata da Eric Albert. Ho usato con successo la classe BrowserLauncher originale in un'applicazione Java multipiattaforma che veniva eseguita localmente con un'interfaccia browser web nei primi anni 2000.
Tieni presente che BrowserLauncher2 è concesso in licenza con GNU Lesser General Public License . Se quella licenza è inaccettabile, cerca una copia del BrowserLauncher originale che ha una licenza molto liberale:
Questo codice è protetto da Copyright 1999-2001 di Eric Albert (ejalbert@cs.stanford.edu) e può essere ridistribuito o modificato in qualsiasi forma senza restrizioni purché la parte di questo commento da questo paragrafo fino alla fine del commento non venga rimossa . L'autore richiede di essere informato di qualsiasi applicazione, applet o altro binario che fa uso di questo codice, ma è più per curiosità che per altro e non è richiesto. Questo software non include alcuna garanzia. L'autore non è responsabile per qualsiasi perdita di dati o funzionalità o per qualsiasi effetto negativo o imprevisto derivante dall'utilizzo di questo software.
Crediti: Steven Spencer, JavaWorld magazine (Java Tip 66) Grazie anche a Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich e Ron Rabakukk
Progetti diversi da BrowserLauncher2 potrebbero anche aver aggiornato il BrowserLauncher originale per tenere conto delle modifiche nel browser e delle impostazioni di sicurezza del sistema predefinite dal 2001.
È molto semplice basta scrivere sotto il codice:
String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
o se non vuoi caricare l'URL, scrivi il nome del tuo browser in valori di stringa come,
String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
aprirà automaticamente il browser con un URL vuoto dopo aver eseguito un programma
Spero non ti dispiaccia, ma ho messo insieme tutte le cose utili, dall'alto, e ho creato una lezione completa pronta per i test ...
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);
}
}
su Windows invoca "cmd / k start http://www.example.com " Infatti puoi sempre invocare programmi "predefiniti" usando il comando start. Ad esempio, start abc.mp3 richiamerà il lettore mp3 predefinito e caricherà il file mp3 richiesto.
I rifusione Brajesh Kumar risposta 's sopra in Clojure come segue:
(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)))))
nel caso sia utile a chiunque.