load file within a jar
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的更多相关文章
- configuration error-could not load file or assembly crystaldecisions.reportappserver.clientdoc
IIS启动网站后报错: configuration error Could not load file or assembly 'crystaldecisions.reportappserver.cl ...
- 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 ...
- Could not load file or assembly 'System.ServiceModel.DomainServices.Hosting'.系统找不到指定文件
项目部署到服务器后出现如下错误信息: Parser Error Message: Could not load file or assembly 'System.ServiceModel.Domain ...
- 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 ...
- 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 数据库服 ...
- 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 ...
- 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 ...
- 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 ...
- System.BadImageFormatException: Could not load file or assembly
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>InstallUtil.exe C:\_PRODUKCIJA\Debug\DynamicHtmlT ...
随机推荐
- 逆向工程-对native层的一次简单逆向实践
关注一款app很久了,这款app为了防止别人逆向破解拉取数据做了很多工作: 防止别人修改apk包,执行关键动作时对dex文件进行md5验证: 防止用户调用接口批量拉数据,对返回的web网页里个人信息进 ...
- elasticSearch6源码分析(3)cluster模块
1. cluser概述 One of the main roles of the master is to decide which shards to allocate to which nodes ...
- eclipse下查看java源码设置
myway: 1.选择一函数,按住ctrl,显示open declaration(或按F3); 2.点进去: 如果未配置,点 source attachment configuration -- ex ...
- Spark2.1.0——内置RPC框架详解
Spark2.1.0——内置RPC框架详解 在Spark中很多地方都涉及网络通信,比如Spark各个组件间的消息互通.用户文件与Jar包的上传.节点间的Shuffle过程.Block数据的复制与备份等 ...
- sql 整理积累
) AS t1 LEFT JOIN (SELECT * FROM dbo.xcqy2017_News_Classification) AS t2 ON t2.Ncid = t1.Ncid left j ...
- jQuery.Form.js 异步提交表单使用总结
jQuery.Form.js 是一个用于使用jQuery异步提交表单的插件,它使用方法简单,支持同步和异步两种方式提交. 第一步:引入jQuery与jQuery.Form.js <script ...
- Vue之组件使用(一)
这仅仅是个人为了防止忘记做的笔记而已,仅供参考,有不对的地方请纠正 组件这种东西用来封装多次使用的控件还是很有用处的,我还是挺喜欢这种模式,优化了前端的工作,写个组件也比较简单.下次有时间记录一下样式 ...
- 理解JVM之垃圾收集器详解
前言 垃圾收集器作为内存回收的具体表现,Java虚拟机规范并未对垃圾收集器的实现做规定,因而不同版本的虚拟机有很大区别,因而我们在这里主要讨论基于Sun HotSpot虚拟机1.6版本Update22 ...
- 集合框架三(List和Set的补充(不加泛型))
List List存放的元素有序,可重复 List list = new ArrayList(); list.add("123"); list.add("456" ...
- php生成word,并下载
1.前端代码 <!DOCTYPE html> <html> <head> <title>PHP生成Word文档</title> <me ...