[英]Including a property file with the Jar file in a single folder
我正在Eclipse Helios中创建一个Java应用程序。我创建了一个类,我需要从.properties文件中获取数据,该文件已添加到包含解决方案的文件夹中。通过此代码,我可以从.properties文件中访问值当我尝试在Eclipse中运行它时。
代码是:
Properties prop = new Properties();
prop.load(new FileInputStream("config.properties"));
_url = prop.getProperty("url");
通过此代码,我得到了正确的Url值。
之后,我创建了我项目的可执行jar。当我尝试使用命令行执行jar时,我得到了FileNotFoundException,这意味着jar无法找到.properties文件。
由于我们提供了编辑.properties文件的功能,因此我已将.properties文件与Jar文件保存在同一文件夹中。
由于我开始用Java工作仅4天,因此我无法弄清楚.properties文件的存放位置以及如何访问它。
请帮忙。
对于jar,请尝试使用:
prop.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
如果从静态上下文调用,请使用:
prop.load(YourClassName.class.getClassLoader().getResourceAsStream("config.properties"));
您需要要求类加载器获取资源。 参见http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html
Properties prop = new Properties();
prop.load(classLoader.getResourceAsStream("config.properties"));
_url = prop.getProperty("url");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.