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.

load file within a jar的更多相关文章

  1. configuration error-could not load file or assembly crystaldecisions.reportappserver.clientdoc

    IIS启动网站后报错: configuration error Could not load file or assembly 'crystaldecisions.reportappserver.cl ...

  2. Could not load file or assembly 'Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its de

    页面加载时出现这个错误: Could not load file or assembly 'Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Cul ...

  3. Could not load file or assembly 'System.ServiceModel.DomainServices.Hosting'.系统找不到指定文件

    项目部署到服务器后出现如下错误信息: Parser Error Message: Could not load file or assembly 'System.ServiceModel.Domain ...

  4. ASP.NET corrupt assembly “Could not load file or assembly App_Web_*

    以下是从overFlow 复制过来的问题 I've read through many of the other questions posted on the same issue, but I s ...

  5. Could not load file or assembly 'Microsoft.SqlServer.Management.Sdk.Sfc, Version=11.0.0.0 系统找不到指定的文件。

    环境: web服务器: ip:192.168.1.32 ,安装有 Visual Studio Premium 2013 操作系统: Microsoft  Server 2008 r2+sp1 数据库服 ...

  6. NopCommerce 发布时 Could not load file or assembly 'file:///...\Autofac.3.5.2\lib\net40\Autofac.dll' or one of its dependencies

    本文转自:http://www.nopcommerce.com/boards/t/33637/4-errors.aspx 问题: The 3.5 solution compiles fine, and ...

  7. Could not load file or assembly 'MySql.Data.CF,

    Could not load file or assembly 'MySql.Data.CF, Version=6.4.4.0, Culture=neutral, PublicKeyToken=c56 ...

  8. Could not load file or assembly 'System.Data.SQLite' or one of its dependencies

    试图加载格式不正确的程 异常类型 异常消息Could not load file or assembly 'System.Data.SQLite' or one of its dependencies ...

  9. System.BadImageFormatException: Could not load file or assembly

    C:\Windows\Microsoft.NET\Framework64\v4.0.30319>InstallUtil.exe C:\_PRODUKCIJA\Debug\DynamicHtmlT ...

随机推荐

  1. java中 immutable,future,nio

    什么是Future? 用过Java并发包的朋友或许对Future (interface) 已经比较熟悉了,其实Future 本身是一种被广泛运用的并发设计模式,可在很大程度上简化需要数据流同步的并发应 ...

  2. 解决U盘拷贝时提示文件过大问题(不能拷贝超过4个g的文件)

    为什么一个16G的U盘却拷不进一个4G大点的文件呢,想必很多朋友们都在疑问? 其实这跟U盘的磁盘格式有关,目前市面上常用的U盘大都是FAT32格式,我们可以查看U盘属性. 那么FAT32是什么呢? F ...

  3. iOS开源项目周报0428

    由OpenDigg 出品的iOS开源项目周报第十八期来啦.我们的iOS开源周报集合了OpenDigg一周来新收录的优质的iOS开源项目,方便iOS开发人员便捷的找到自己需要的项目工具等. Bouncy ...

  4. [转]sp_OACreate WriteLine Writing nvarchar 中文汉字 非乱码to a text file

    本文转自:https://stackoverflow.com/questions/48135889/writing-nvarchar-to-a-text-file According to the S ...

  5. 安装jdk出现问题:Error opening registry key'software\Javasoft\Java Runti...

    重装系统后发现jdk没有了,重新安装了,装一个其实挺容易的,但是“java -version”回车的时候,“啪”,error: Error opening registry key'software\ ...

  6. Java Switch支持的类型问题

    常见支持类型为int,byte,short,char及枚举类型.以上是JDK1.6以前的版本.JDK1.7时,又增加了String. 参考资料:1.java switch支持的数据类型 2.java中 ...

  7. 撩课-Web大前端每天5道面试题-Day30

    1.什么叫优雅降级和渐进增强? 优雅降级: Web站点在所有新式浏览器中都能正常工作, 如果用户使用的是老式浏览器, 则代码会针对旧版本的IE进行降级处理了, 使之在旧式浏览器上以某种形式降级体验却不 ...

  8. centos7下没有iptables

    从centos7开始使用linux,之前版本的没有深入了解过,今天要开放个端口,需要有防火墙的相关操作,从网上查资料都是编辑/etc/sysconfig目录下面的iptables文件,可我进入这个文件 ...

  9. Graveyard(poj3154)

    Graveyard Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 1289   Accepted: 660   Specia ...

  10. 手机网页meta,添加使其兼容各种浏览器

    虽然手机不像电脑那样会有各种低版本的浏览器,但写手机端网页也是需要注意的: <!-- 优先使用 IE 最新版本和 Chrome --> <meta http-equiv=" ...