簡體   English   中英

從Java程序打開瀏覽器窗口

[英]Open Browser window from Java program

我有一個用Java編寫的應用程序。 它被設計為獨立運行在Linux機器上。 我正在嘗試生成一個新的firefox窗口。 但是, Firefox從未打開過。 它總是有一個shell退出代碼1.我可以使用gnome-terminal運行相同的代碼,它打開正常。

背景

所以,這是它的初始化過程:

  1. 開始X“Xorg:1 -br -terminate -dpms -quiet vt7”
  2. 啟動窗口管理器“metacity --display =:1 --replace”
  3. 配置資源“xrdb -merge / etc / X11 / Xresources”
  4. 成為守護進程並斷開與控制終端的連接

一旦程序運行起來,用戶可以點擊一個按鈕來生成一個firefox窗口。 這是我的代碼。 記得X在顯示器上運行:1。


public boolean openBrowser()
{
  try {
    Process oProc = Runtime.getRuntime().exec( "/usr/bin/firefox --display=:1" );
    int bExit = oProc.waitFor();  // This is always 1 for some reason

    return true;

  } catch ( Exception e ) {
    oLogger.log( Level.WARNING, "Open Browser", e );
    return false;
  }
}

如果您可以將其縮小到Java 6,則可以使用桌面API:

http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/

應該看起來像:

    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.BROWSE)) {
            try {
                desktop.browse(new URI("http://localhost"));
            }
            catch(IOException ioe) {
                ioe.printStackTrace();
            }
            catch(URISyntaxException use) {
                use.printStackTrace();
            }
        }
    }

使用BrowserLauncher

調用它非常簡單,只需去

new BrowserLauncher().openURLinBrowser("http://www.google.com");

在閱讀了各種答案和各種評論后(來自提問者),這就是我要做的

1)嘗試這種java方法http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("myDir");
Process p = pb.start();

詳細了解這個課程:

http://java.sun.com/developer/JDCTechTips/2005/tt0727.html#2
http://www.javabeat.net/tips/8-using-the-new-process-builder-class.html

2)嘗試從C / C ++ / ruby​​ / python執行此操作(啟動firefox),看看是否成功。

3)如果所有其他方法都失敗了,我會啟動一個shell程序,那個shell程序會啟動firefox !!

如果您閱讀並顯示標准輸出/錯誤流,您可能會有更好的運氣,因此您可以捕獲firefox可能打印的任何錯誤消息。

try {
     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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM