从jar里提取资源

使用Java时经常会碰到需要从jar文件里提取资源的情况。Java里提供了getClass().getResource()和getResourceAsStream()这两个函数来读取jar里的文件。但有时候要是不是直接使用该资源,而是需要把资源文件名称位置传递给第三方的时候就不怎么方便了。下面这个帮助函数把资源文件先提取出来储存在一个临时文件里用来继续加工。getResourceFile返回的File为该资源的临时文件:

如从jar里提取根目录下的cfg.properties文件:File cfgFile = getResourceFile(“/cfg.properties”);

public final File getResourceFile(String resourceFile) {
try {
File tmpFile = File.createTempFile("resource", null);
writeStream(getClass().getResourceAsStream(resourceFile), tmpFile);
return tmpFile;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

private static final void writeStream(InputStream in, File file) throws IOException {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
int len;
byte[] buffer = new byte[1024 * 8];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.close();
}
Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s