Java examples for Native OS:Browser
Save the provided string as the entire contents of a file, then have this desktop's default browser display the file as HTML.
import java.awt.Desktop; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URI; public class Main{ public static void main(String[] argv) throws Exception{ String html = "java2s.com"; render(html);//w ww.ja va2 s . c om } public static final String defaultFileName; public static final String HTML_HEADER = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"" + "\"http://www.w3.org/TR/html4/strict.dtd\">\n"; /** * Save the provided string as the entire contents of a file, then * have this desktop's default browser display the file as HTML. * * @param html the string containing the HTML text. * * Preconditions: * The string should contain legal HTML. * The string's outermost tag should be "<html>...</html>". */ public static void render(String html) { if (Desktop.isDesktopSupported()) { try { FileWriter fw = new FileWriter(defaultFileName); fw.write(HTML_HEADER); fw.write(html); fw.close(); } catch (IOException ioe) { System.err.println(ioe); ioe.printStackTrace(); } Desktop dt = Desktop.getDesktop(); URI uri; try { uri = new File(defaultFileName).toURI(); dt.browse(uri); } catch (IOException e) { System.err.println("Error: cannot open file://" + defaultFileName + '.'); } } else { System.err .println("Error: unable to open browser in this environment."); } } }