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
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...