簡體   English   中英

在JAR文件中時,URL getResource無法正常工作

[英]URL getResource not working when in JAR file

我的應用程序加載了PROJECTNAME/resource文件夾中的txt文件。

在此處輸入圖片說明

這是我加載文件的方式:

URL url = getClass().getClassLoader().getResource("batTemplate.txt");
java.nio.file.Path resPath;
String bat = "";

try {
    resPath = java.nio.file.Paths.get(url.toURI());
    bat = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");
} catch (URISyntaxException | IOException e1) {
        e1.printStackTrace();
}

注意:這在我從Eclipse運行時有效,而在我導出到Jar文件(將所需的庫提取到生成的JAR中)時不起作用。 我知道該文件正在提取中,因為它在JAR文件中。 圖像也起作用。

在此處輸入圖片說明

錯誤MSG:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
    Illegal character in path at index 38: file:/C:/DataTransformation/Reports Program/ReportsSetup.jar
        at com.sun.nio.zipfs.ZipFileSystemProvider.uriToPath(ZipFileSystemProvider.java:87)
        at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:166)
        at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
        at java.nio.file.Paths.get(Unknown Source)
        at ReportSetup$13.mouseReleased(ReportSetup.java:794)

我在這里也看到了類似的問題,但是它們引用的是JAR文件之外的文件/ URL。

.jar條目不是文件; 它是.jar存檔的一部分。 無法將資源轉換為Path。 您將要使用getResourceAsStream來閱讀它。

要閱讀所有內容,您有一些選擇。 您可以使用掃描儀:

try (Scanner s = new Scanner(getClass().getClassLoader().getResourceAsStream("batTemplate.txt"), "UTF-8")) {
    bat = s.useDelimiter("\\Z").next();
    if (s.ioException() != null) {
        throw s.ioException();
    }
}

您可以將資源復制到一個臨時文件中:

Path batFile = Files.createTempFile("template", ".bat");
try (InputStream stream = getClass().getClassLoader().getResourceAsStream("batTemplate.txt")) {
    Files.copy(stream, batFile);
}

您可以簡單地從InputStreamReader中讀取文本:

StringBuilder text = new StringBuilder();
try (Reader reader = new BufferedReader(
    new InputStreamReader(
        getClass().getClassLoader().getResourceAsStream("batTemplate.txt"),
        StandardCharsets.UTF_8))) {

    int c;
    while ((c = reader.read()) >= 0) {
        text.append(c);
    }
}

String bat = text.toString();

我認為您應該嘗試getClass()。getResourceAsStream(“ / batTemplate.txt”)。

還要檢查一下 可能有幫助。

暫無
暫無

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

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