jar包读取配置文件找不到错误

    有时候开发一些小工具,需要去读取配置文件,但是打完的jar包经常会出现找不到路径的问题,

会想到两种方法:

  1. 把文件放到jar包之外同一目录下,比如 config/ config.properties 文件。
  2. 或者把config.properties文件也打进jar包,


方法1:此时肯定需要压缩文件jar包和这个配置文件一起提供给产品,否则产品不知道如何配置。比较麻烦。

方法2:这种方式比较简便,也是推荐做法

Properties文件加载文件时:

  • 将此配置文件放入src目录下(或者放入其他目录,但是配置成src源代码目录)
  • 用此种方式进行获取,

public class ReadProperties {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Properties properties = new Properties();
		InputStream isInputStream = ReadProperties.class.getClassLoader().getResourceAsStream("config.properties");
		try {
			properties.load(isInputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		System.out.println(properties.getProperty("aa"));
	}
}

也可以采用ResourceBundle的方式来读取资源文件:

public class PropertiesUtil {
	private static final String BUNDLE_NAME = "com.zlp.utils.config";
	
	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			System.out.println(RESOURCE_BUNDLE.getString("aa"));
		} catch (MissingResourceException e) {
			
			System.out.println("can not found file");
		}
	}

}

此时要求资源文件为 config.properties.并且位于目录com.zlp.utils目录下。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,当你需要从一个jar包读取外部配置文件时,你可以采取以下步骤: 1. 确定配置文件的位置:首先,你需要确定配置文件的存放位置。配置文件通常放在项目的资源目录下(例如`src/main/resources`),打包成jar后,这些资源文件会位于jar包的`META-INF`目录下。 2. 获取资源流:在你的Java代码中,你可以使用类加载器(ClassLoader)来获取资源文件的输入流。可以使用`Thread.currentThread().getContextClassLoader()`或者`getClass().getClassLoader()`来获取当前线程的上下文类加载器或当前类的类加载器。 3. 读取文件内容:有了输入流之后,你可以使用IO流(如`BufferedReader`)来读取配置文件的内容。 下面是一个示例代码,展示如何在Java中读取位于`META-INF`目录下的配置文件`config.properties`: ```java import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.Properties; public class ConfigReader { public static Properties readConfig() { Properties config = new Properties(); try { // 使用当前类的类加载器获取资源输入流 InputStream inputStream = ConfigReader.class.getClassLoader().getResourceAsStream("META-INF/config.properties"); if (inputStream == null) { throw new RuntimeException("No config.properties found in the classpath."); } config.load(new InputStreamReader(inputStream, "UTF-8")); } catch (Exception e) { e.printStackTrace(); } return config; } public static void main(String[] args) { Properties config = readConfig(); // 输出读取到的配置信息,例如: System.out.println(config.getProperty("key")); } } ``` 请注意,配置文件读取可能会出现文件不存在、文件读取错误等情况,因此应当妥善处理这些异常情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值