簡體   English   中英

上傳位於 jar 內的文件

[英]Upload a file located inside a jar

我正在嘗試上傳位於 jar 中的文件。 當我正常上傳文件時,它工作正常(這是預期的,因為文件在文件系統上)但是當我打包一個帶有位於其中的文件的 jar 時它不起作用。 我試過使用:

this.getClass().getClassLoader().getResource("big_bird.txt") //不起作用

new File("big_bird.txt".toURI()) //不起作用

this.getClass().getClassLoader().getResourceAsStream("big_bird.txt") //有點像我看到路徑但我無法獲取文件

我需要能夠抓取文件並將其全部上傳到 jar 中,所以任何人都可以讓我深入了解如何做到這一點?

  1. 從 jar 中以流的形式讀取文件

InputStream in = getClass().getResourceAsStream("big_bird.txt");

  1. 創建臨時文件

File tempFile = File.createTempFile("big_bird", "txt");

  1. 將輸入流寫入臨時文件
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
    int read;
    byte[] bytes = new byte[1024];
    while ((read = in.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
}
  1. 現在您可以使用/上傳tempFile

暫無
暫無

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

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