如何访问JAR包中的资源文件

转载:[url]http://hi.baidu.com/triceratops/blog[/url]
JAR文件本质上是一种ZIP格式的文件,有些时候java程序需要访问JAR包中的某资源文件(例如properties文件),但此时是不能使用File类来操作的,这是因为File类是不能访问压缩包内的文件路径的。一种办法是利用java.util.zip 或者java.util.jar 包中的API操作JAR包,但是代码写起来比较麻烦;还有一种更简单的方法是利用Class类的getResourceAsStream(String name)方法来访问jar包内的资源。一个简单的示例如下:


package cn.edu.ustb.math;

import java.io.*;

public class AccessJar{
public void backupResourceFile(String resourceName) throws IOException{
//load resource as bytes
InputStream is = getClass().getResourceAsStream(resourceName);
//The InputStream instance will be different for folder path and jar file path
System.out.println(is.getClass().getName());
//backup resource
OutputStream fos = new FileOutputStream((resourceName.startsWith("/")?
resourceName.substring(1):resourceName)+".bak");
byte[] buf = new byte[1024];
int i;
while((i=is.read(buf))!=-1){
fos.write(buf, 0, i);
}
fos.close();
}

public static void main(String[] args){
try{
new AccessJar().backupResourceFile("/fr-019-v110.exe");
/**
If the file name begins with a '/' ('\u002f'), then the absolute name of
the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object
with '/' substituted for '.' ('\u002e').
*/
System.out.println("Done!");
}
catch(IOException e){
e.printStackTrace();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值