2009-03-02 17 views

Respuesta

39

Si está utilizando Java 6 o superior, consulte la API Desktop, en particular browse. Utilizar de esta manera (no probado):

// using this in real life, you'd probably want to check that the desktop 
// methods are supported using isDesktopSupported()... 

String htmlFilePath = "path/to/html/file.html"; // path to your new file 
File htmlFile = new File(htmlFilePath); 

// open the default web browser for the HTML page 
Desktop.getDesktop().browse(htmlFile.toURI()); 

// if a web browser is the default HTML handler, this might work too 
Desktop.getDesktop().open(htmlFile); 
+0

Hey. Todavía no puedo hacer que funcione. Aparece el siguiente error: "Mensaje de error: el sistema no puede encontrar la ruta especificada". Esto es a pesar de que le he dado el camino exacto. –

+0

@TheSpecialOne - ¿está suministrando una ruta _local_ al archivo? por ejemplo: en un cuadro de Windows, htmlFilePath se vería como "c: \ path \ to \ file.html". No use la sintaxis de URL ... –

0

He usado BrowserLauncher2 con éxito. Invocará el navegador predeterminado en todas las plataformas probadas. Lo uso para el software de demostración a través de JNLP. El software descarga, ejecuta y conduce el navegador del usuario a páginas de información/comentarios, etc.

JDK 1.4 y superior, creo.

+0

Si la URL de la página cambia debido a la actividad del usuario, ¿puede obtener esa nueva URL usando BrowserLauncher2? –

26

Ya, pero si desea abrir la página web en su navegador web predeterminado mediante un programa java, puede intentar usar este código.

/// file OpenPageInDefaultBrowser.java 
public class OpenPageInDefaultBrowser { 
    public static void main(String[] args) { 
     try { 
     //Set your page url in this string. For eg, I m using URL for Google Search engine 
     String url = "http://www.google.com"; 
     java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); 
     } 
     catch (java.io.IOException e) { 
      System.out.println(e.getMessage()); 
     } 
    } 
} 
/// End of file 
2

sé que todas estas respuestas, básicamente, han respondido a la pregunta, pero aquí es un código de un método que falla con gracia.

Tenga en cuenta que la cadena puede ser la ubicación de un archivo html

/** 
* If possible this method opens the default browser to the specified web page. 
* If not it notifies the user of webpage's url so that they may access it 
* manually. 
* 
* @param url 
*   - this can be in the form of a web address (http://www.mywebsite.com) 
*   or a path to an html file or SVG image file e.t.c 
*/ 
public static void openInBrowser(String url) 
{ 
    try 
     { 
      URI uri = new URL(url).toURI(); 
      Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; 
      if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { 
       desktop.browse(uri); 
      } else { 
       throw new Exception("Desktop not supported, cannout open browser automatically"); 
      } 
     } 
    catch (Exception e) 
     { 
      /* 
      * I know this is bad practice 
      * but we don't want to do anything clever for a specific error 
      */ 
      e.printStackTrace(); 

      // Copy URL to the clipboard so the user can paste it into their browser 
      StringSelection stringSelection = new StringSelection(url); 
      Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); 
      clpbrd.setContents(stringSelection, null); 
      // Notify the user of the failure 
      WindowTools.informationWindow("This program just tried to open a webpage." + "\n" 
       + "The URL has been copied to your clipboard, simply paste into your browser to access.", 
        "Webpage: " + url); 
     } 
} 
Cuestiones relacionadas