簡體   English   中英

Java:使用OS標准應用程序打開jar中的資源(txt文件)

[英]Java: opening a resource (txt file) which is in a jar with OS standard application

我收到錯誤“ AWT-EventQueue-0 java.lang.IllegalArgumentException:URI不分層”。 -我正在嘗試使用java.awt.Desktop api使用操作系統的默認應用程序打開文本文件。 -我正在運行的應用程序是從autorunning jar啟動的。 我了解從文件中獲取“文件”不是正確的方法,並且將其稱為資源。 我仍然無法打開它,也無法弄清楚該怎么做。

open(new File((this.getClass().getResource("prova.txt")).toURI()));

有沒有辦法從我的應用程序中使用標准os應用程序打開資源? 謝謝 :)

您必須將文件從Jar中提取到temp文件夾中,然后打開該臨時文件,就像處理Zip文件(Jar基本上是Zip文件)中的文件一樣。

您不必將文件解壓縮到/ tmp文件夾。 您可以使用`getClass()。getResourceAsStream()'直接讀取它。 但請注意,路徑取決於txt文件的位置以及類的包。 如果您的txt文件打包在jar的根目錄中,請使用'“ /prova.txt”'。 (注意斜杠)。

我認為您無法使用外部應用程序打開它。 據我所知,所有安裝程序都將其壓縮內容提取到臨時位置,然后將其刪除。

但是您可以使用Class.getResource(String name)在Java代碼中完成此操作

http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String

錯誤

open(new File((this.getClass().getResource("prova.txt")).toURI()));

EULA

/**

Do you accept the License Agreement of XYZ app.?

*/
import java.awt.Dimension;
import javax.swing.*;

import java.net.URL;
import java.io.File;
import java.io.IOException;

class ShowThyself {

    public static void main(String[] args) throws Exception {
        // get an URL to a document..
        File file = new File("ShowThyself.java");
        final URL url = file.toURI().toURL();

        // ..then do this
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                JEditorPane license = new JEditorPane();
                try {
                    license.setPage(url);
                    JScrollPane licenseScroll = new JScrollPane(license);
                    licenseScroll.setPreferredSize(new Dimension(305,90));

                    int result = JOptionPane.showConfirmDialog(
                        null,
                        licenseScroll,
                        "EULA",
                        JOptionPane.OK_CANCEL_OPTION);
                    if (result==JOptionPane.OK_OPTION) {
                        System.out.println("Install!");
                    } else {
                        System.out.println("Maybe later..");
                    }
                } catch(IOException ioe) {
                    JOptionPane.showMessageDialog(
                        null,
                        "Could not read license!");
                }
            }
        });
    }
}

如果您要傳遞的內容可以接受java.net.URL則可以使用:

this.getClass().getResource("prova.txt")).toURI().toURL()

JDK提供了JarFileJarEntry類。 這允許從JarFile加載文件。

JarFile jarFile = new JarFile("jar_file_Name");
JarEntry entry = jarFile.getJarEntry("resource_file_Name_inside_jar");
InputStream stream = jarFile.getInputStream(entry); // this input stream can be used for specific need

暫無
暫無

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

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