Java:如何在可运行的Jar文件中打包和访问资源? [英] Java: How to package and access resources inside a runnable Jar file?

查看:238
本文介绍了Java:如何在可运行的Jar文件中打包和访问资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java控制台应用程序与资源文件夹。它可以正常工作,但是当我想将我的代码导出到一个可运行的Jar文件(使用Eclipse)时,导出的Jar无法找到这些文件(它们在buildpath中)并提供了Filenotfound异常。



当我解压缩导出的Jar文件时,我可以看到文件在根文件夹中,所以我猜我的代码有问题。

  BufferedReader srcFile = new BufferedReader(new FileReader(resources /+ filename)); 
String line = srcFile.readLine();

我尝试使用

  URL url = ClassLoader.getSystemResource(filename); 
filename = url.tostring();

但没有运气。

解决方案

使用 getResourceAsStream(String)(docs)如果你想阅读类路径中的资源。


I have a Java console applicaton with a resources folder. It works OK, but when I want to export my code to a runnable Jar file(with Eclipse), then the exported Jar can not find the files(they are in buildpath) and give a Filenotfound exception.

When I unzip the exported Jar file I can see the files are there in the root folder, so I guess something wrong with my code.

BufferedReader srcFile = new BufferedReader(new FileReader("resources/"+filename));
String line = srcFile.readLine();

I tried to use

URL url= ClassLoader.getSystemResource(filename);
filename=url.tostring();        

But no luck.

解决方案

Use getResourceAsStream(String) (docs) if you want to read in a resource on the classpath.

这篇关于Java:如何在可运行的Jar文件中打包和访问资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆