簡體   English   中英

無法從 spring boot .jar 讀取文件

[英]Unable to read file from spring boot .jar

我想訪問生產服務器上 jar 中名為reports/invoiceSweetChoice.jasper類路徑上的文件。 無論我做什么,我都會得到空值。

我已經嘗試過this.getClass().getResourceAsStream("reports/invoiceSweetChoice.jasper") ,通過InputStream等嘗試過。我已經打印出System.getProperty("java.class.path") ,它是空的。 不知道這怎么可能。 你有什么建議如何解決這個問題嗎?

@Autowired private ResourceLoader resLoad;


void someMethod() {
    Resource r = resLoad.getResource("classpath:reports/file.abc");
    r.getInputStream()...
    ...

在 manifest.mf 中,類路徑是使用class-path 鍵和空格分隔的文件列表定義的,如下所示:

jarfile 根目錄下的 MANIFEST.MF。

Class-Path: hd1.jar path/to/label007.jar path/to/foo.jar

如果 jar 文件名中有空格,則應將它們括在引號中。

如果它是一個 web 應用程序,報告路徑應該在你的類路徑的 BOOT-INF 子目錄中——如果你把它放在標准布局的 src/main/resources 中,這將由 maven 自動執行。

編輯:

現在您已經闡明了您要做什么,您有兩種方法。 就像我上面說的,您可以從 web 應用程序的 BOOT-INF 子目錄中獲取文件,或者您可以枚舉 jar 中的條目,直到找到您想要的條目:

JarInputStream is = new JarInputStream(new FileInputStream("your/jar/file.jar"));
JarEntry obj = null
while ((obj = is.getNextJarEntry()) != null) {
   JarEntry entry = (JarEntry)obj;
   if (entry.getName().equals("file.abc")) {
        ByteArrayOutputStream baos = new ByetArrayOutputStream(); 
        IOUtils.copy(jarFile.getInputStream(entry), baos);
        String contents = new String(baos.toByteArray(), "utf-8");
        // your entry is now read into contents
   }
}

暫無
暫無

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

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