java读取外部properties文件_jar包读取外部properties文件

该博客介绍了一个Java工具类,用于在jar包环境下动态读取外部的conn.properties配置文件。当配置文件位于项目路径下时优先读取,否则从classpath中加载。提供了一个名为`PropertiesUtils`的类,包含`getValue`方法获取配置项和`loadConfProperties`方法初始化配置文件的加载。
摘要由CSDN通过智能技术生成

将自身部分功能打成jar包时,需要动态从外部读取配置文件。

此工具类优先从项目路径下读取配置文件,读取不到时从classpath获取配置文件。

使用方式:

开发时直接读取项目资源目录下的 properties即可

打成jar包使用时,将配置文件与jar包放置在同一目录

代码:

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

public class PropertiesUtils {

/**

* properties

*/

private static Properties properties = null;

/**

* 根据key获取value值

*

* @param key

* @return

*/

public static String getValue(String key) {

if (properties == null) {

properties = loadConfProperties();

}

String value = properties.getProperty(key);

System.out.print

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、付费专栏及课程。

余额充值