Подтвердить что ты не робот

Как открыть HTML файл с помощью Java?

Я пытаюсь открыть HTML файл из локальной (в моей системе) программы Java. Я попробовал некоторые из программы, полученные через переполнение стека, но это не работает.

Для EG: У меня есть этот небольшой HTML файл.

<html>
  <head> 
    Test Application
  </head>
  <body>
     This is test application
  </body>
</html>

Мой код Java:

Runtime rTime = Runtime.getRuntime();
String url = "D:/hi.html";
String browser = "C:/Program Files/Internet Explorer/iexplore.exe ";
Process pc = rTime.exec(browser + url);
pc.waitFor();

Любое решение или советы оценены.

4b9b3361

Ответ 1

Я бы предпочел использовать браузер по умолчанию

File htmlFile = new File(url);
Desktop.getDesktop().browse(htmlFile.toURI());

Ответ 2

Вот код для метода, который изящно выходит из строя.

Обратите внимание, что строка может быть расположением html файла.

/**
* If possible this method opens the default browser to the specified web page.
* If not it notifies the user of webpage 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);
        }
    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);
        }
}

Ответ 3

URI oURL = new URI(url);
Desktop.getDesktop().browse(oURL);

Кроме того, убедитесь, что файл уже открыт в нужном браузере. Проверьте значок в файле, если он отображается как текстовый файл, вы, возможно, уже открыли текстовый файл. Поэтому измените программу по умолчанию на нужную программу.