load file within a jar

来源:https://www.cnblogs.com/kungfupanda/archive/2018/08/14/9472064.html
-Advertisement-
Play Games

String examplejsPrefix = "example"; String examplejsSuffix = "js"; String examplejs = examplejsPrefix + "." + examplejsSuffix; try { // save it as a t ...


String examplejsPrefix = "example";
String examplejsSuffix = "js";
String examplejs = examplejsPrefix + "." + examplejsSuffix;

try {

// save it as a temporary file so the JVM will handle creating it and deleting
File file = File.createTempFile(examplejsPrefix, examplejsSuffix);
file.deleteOnExit();
OutputStream out = new FileOutputStream(file);

InputStream in = getClass().getResourceAsStream("/com/" + examplejs);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}

===============

https://alvinalexander.com/blog/post/java/read-text-file-from-jar-file

 

Java jar file reading FAQ: Can you show me how a Java application can read a text file from own of its own Jar files?

Here's an example of some Java code I'm using to read a file (a text file) from a Java Jar file. This is useful any time you pack files and other resources into Jar files to distribute your Java application.

How to read a Java Jar file, example #1

The source code to read a file from a Java Jar file uses the getClass and getResourceAsStream methods:

  public void test3Columns()
  throws IOException
  {
    InputStream is = getClass().getResourceAsStream("3Columns.csv");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null) 
    {
      CSVLineTokenizer tok = new CSVLineTokenizer(line);
      assertEquals("Should be three columns in each row",3,tok.countTokens());
    }
    br.close();
    isr.close();
    is.close();
  }

The trick to reading text files from JAR files are these lines of code, especially the first line:

InputStream is = getClass().getResourceAsStream("3Columns.csv");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

In my example I have a plain text file named "3Columns.csv" in the same directory as the class that contains this method. Without a path stated before the filename (like "/foo/bar/3Columns.csv") the getResourceAsStreammethod looks for this text file in its current directory.

 

Note that I'm doing all of this within the context of a JUnit test method. Also note that I'm throwing any exceptions that occur rather than handling them. I don't recommend this for real world programming, but it works okay for my unit testing needs today.

I haven't read through the Javadocs yet to know if all of those closestatements at the end are necessary. I'll try to get back to that later.

Java: How to read a Jar file, example #2

Here is a slightly more simple version of that method:

public String readFromJARFile(String filename)
throws IOException
{
  InputStream is = getClass().getResourceAsStream(filename);
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr);
  StringBuffer sb = new StringBuffer();
  String line;
  while ((line = br.readLine()) != null) 
  {
    sb.append(line);
  }
  br.close();
  isr.close();
  is.close();
  return sb.toString();
}

In this sample I've eliminated the CSVLineTokenizer and replaced it with a simple StringBuffer, and I return a plain old String at the end of the method.

Also, if I didn't stress it properly earlier, with this approach the resource file that you're trying to read from must be in the same directory in the jar file as this class. This is inferred by the getClass().getResourceAsStream()method call, but I don't think I really stressed that enough earlier.

Also, I haven't looked at it in a while, but I think you can just call the is.close() method to close all your resources, you don't have to make all the close calls I make here, but I'm not 100% positive.

Reading a file from a jar file as a File

Here's one more example of how to do this, this time using some code from a current Scala project:

val file = new File(getClass.getResource("zipcode_data.csv").toURI)

Although the code shown is Scala, I think you can see that you can use this approach to read the file as a java.io.File instead of reading it as a stream.

One more Java "read from Jar file" example

While I'm working on another Java project, I just ran across another example of how to read a file from a Java jar file in this method:

private void playSound(String soundfileName)
{
  try
  {
    ClassLoader CLDR = this.getClass().getClassLoader();
    InputStream inputStream = CLDR.getResourceAsStream("com/devdaily/desktopcurtain/sounds/" + soundfileName);
    AudioStream audioStream = new AudioStream(inputStream);
    AudioPlayer.player.start(audioStream);
  }
  catch (Exception e)
  {
    // log this
  }
}

As you can guess from looking at this code, this example shows how to read a resource file from a jar file in a java application, and in this approach, the resource file that I'm reading doesn't have to be in the same directory as the Java class file. As you can imagine, this is a much more flexible approach.


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 此文是我的出版書籍[《React Native 精解與實戰》](http://rn.parryqiu.com/)連載分享,此書由機械工業出版社出版,書中詳解了 React Native 框架底層原理、React Native 組件佈局、組件與 API 的介紹與代碼實戰,以及 React Native... ...
  • cropperjs的高度過大(container height too much) ...
  • 近幾年的的微服務概念大火特火,隨之框架也變得大火起來,尤其是spring boot,可能是因為spring cloud火起來的原因 搞得沉寂多年的dubbo也開始更新變得火起來。 說起微服務對於不瞭解整個系統架構歷史的小伙伴可能有些迷惑,怎麼就突然一下子就微服務了,有點摸不著頭腦,到底咋回事那?聽我 ...
  • 《劍指offer》: 首先熟悉一下java自帶的進位之間轉換的api: /*java中進行二進位,八進位,十六進位,十進位間進行相互轉換十進位轉成十六進位:Integer.toHexString(int i)十進位轉成八進位Integer.toOctalString(int i)十進位轉成二進位In ...
  • 問題:通常會遇到這樣一個問題,就是svn伺服器不能以SVN 協議訪問,而只能用https協議訪問。 主要原因是svn服務端集成了apache的安裝包,安裝後自動配置成了http協議訪問。如果需要svn協議訪問,則需要重新架設svn版本管理伺服器,不能集成apache,使用純svn安裝包即 “ sub ...
  • zendstudio 10.0破解版,新建完項目後,首先修改項目的編碼方式,統一改成utf-8 (選中項目,再右鍵properties:Text file encoding)。修改字體大小。 apache 安裝:httpd-2.2.17-win32,安裝成功後訪問apache伺服器:http://1 ...
  • 1. Java 中File類的createNewFile()與createTempFile()的區別 最近,在看代碼時看到了一個方法, File.createTempFile() ,由此聯想到File.createNewFile() 方法,一時間不知道兩者到底有什麼區別,感覺都是創建新文件嘛,後來查 ...
  • You can do this using a JLabel, but an alternative would be to style a JButton. That way, you don't have to worry about accessibility and can just fir ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...