簡體   English   中英

Java 無法使用運行時打開 pdf

[英]Java unable to open pdf using Runtime

我必須在單擊 JMenuItem 時打開 pdf。 如果我從 netbeans 運行我的程序,我可以在單擊菜單項時打開 pdf。 但是當我從 jar 文件運行時,它沒有打開。 我清理並構建我的項目。 但沒有變化。 從 netbeans 運行但不從 jar 文件運行時運行。 我需要添加一些庫嗎?

我的代碼如下

m_aboutItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Runtime rt = Runtime.getRuntime();
           //System.out.println(Menubar1.getDefaultLocale());
                URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
                String link=link2.toString();
                link=link.substring(6);
                System.out.println(link);
                System.out.println(link2);
                String link3="F:/new/build/classes/newpkg/Documentation.pdf";
                try {
                Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link2);
            } catch (IOException ex) {
                Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

也試過這個但得到同樣的東西..當我從 netbeans 但不能從 jar 應用程序運行時,我可以從 menuitem 打開 pdf。

m_aboutItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
                String link=link2.toString();
                link=link.substring(6);
                System.out.println(link); 
            File file=new File(link);
            System.out.println(file);
                try {
                    desktop.open(file);
                } catch (IOException ex) {
                    Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
    });

對於第二個代碼,從 netbeans 運行時,所有 system.out.println() 的 output 如下所示

run:

F:/new/build/classes/newpkg/Documentation.pdf F:\new\build\classes\newpkg\Documentation.pdf 構建成功(總時間:5 秒)

rundll32.exe無法處理現在位於 Jar 內的資源。 檢查getResource(String)返回的 URL 。

..但仍然無法正常工作..

問題在於,至少對於 PDF, rundll32僅適用於File實例。 使用(例如顯示)PDF 的工具通常不是為接受命令行參數而設計的。 代表URL 如果URL應該指向File ,則該過程可以繼續。 但是一旦 PDF 在 Jar 中,它就只是 Jar 中的一個條目。 或者換句話說,它不是File

如果該推理是正確的,在默認軟件中顯示 PDF 的一種方法是:

  1. 立即將 URL 獲取到URL
  2. 檢查URL指向 Jar(它將包含“.”)。 如果是這樣..
    1. 從 Jar 中提取 PDF 到磁盤上的(臨時) File
  3. 顯示(可能是臨時的) File

能用Java 6和Desktop API嗎?

在啟動時,您可以將文件導出或下載到磁盤嗎?

 try                                      //try statement
     {
         Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "c:\\chart.pdf");   //open the file chart.pdf

     } catch (Exception e)                    //catch any exceptions here
       {
           System.out.println("Error" + e );  //print the error
       }

暫無
暫無

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

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