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 getResourceAsStream
method 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 close
statements 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 ...
随机推荐
- Java中数据类型转换大全(个人总结)
一.字符串转换为其他类型 1.将字符串转化为int型 (1)方法一 int i = Integer.parseInt(String str); (2)方法二 int i = Integer.value ...
- TCP长连接的一些事儿
1.TCP的特点以及与应用 TCP提供一种面向连接的.可靠的字节流服务.面向连接意味着两个使用TCP的应用(通常是一个客户和一个服务器)在彼此交换数据包之前必须先建立一个TCP连接.TC ...
- 求XF+闭包(第十一届河南省省赛真题)
题目描述 如何设计一个好的数据库不仅仅是一个理论研究问题,也是一个实际应用问题.在关系数据库中不满足规范化理论的数据库设计会存在冗余.插入异常.删除异常等现象. 设R(U)是一个关系模式,U={ A1 ...
- 分布式理论(五)—— 一致性算法 Paxos
前言 Paxos 算法如同我们标题大图:世界上只有一种一致性算法,就是 Paxos.出自一位 google 大神之口. 同时,Paxos 也是出名的晦涩难懂,推理过程极其复杂.楼主在尝试理解 Paxo ...
- WCF 获取客户端IP
public class Service2 : IService2 { public User DoWork() { Console.WriteLine(ClientIpAndPort()); }; ...
- 无责任Windows Azure SDK .NET开发入门(二):使用Azure AD 进行身份验证
<編者按>本篇为系列文章,带领读者轻松进入Windows Azure SDK .NET开发平台.本文为第二篇,将教导读者使用Azure AD进行身分验证.也推荐读者阅读无责任Windows ...
- ABB机器人---PCSDK简介
BB机器人为用户提供了大量便捷的二次开发及应用工具,PCSDK就是其中一项. 1) 首先,机器人使用PCSDK,必须要有pc interface选项. 2)此处举例使用C#编写简单界面,实现与机器人数 ...
- Oracle11g自带的SQL_developer无法打开
在安装完Oracle Database 11g Release 2数据库,想试一下Oracle自带的SQL DeveloperW工具,在操作系统菜单的所有程序中找到SQL Developer如下所示, ...
- pdf.js 使用汇总
https://www.cnblogs.com/iPing9/p/7154753.htmlhttp://blog.csdn.net/m0_38021128/article/details/708684 ...
- Java基础——GUI编程(三)
接着前两篇学习笔记,这篇主要介绍布局管理器和对话框两部分内容. 一.布局管理器 先拿一个小例子来引出话题,就按照我们随意的添加两个按钮来说,会产生什么样的效果,看执行结果. import java.a ...