用Properties读取.propertoes文件内容

在工作过程中发现开发组的读取配置文件的工具类流程太繁琐,里面的逻辑竟然看了好多遍都看不太懂,个人觉得逻辑不够清晰,因此想要简化一下读取文件的方法,并且让路径变得可控.

废话不多说,下面上代码:

我事先在util包下和templates包下新建了两个内容为name=jack的配置文件.

在Test类的主方法分别调用绝对路径和相对路径的方法,读取配置文件:

package com.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @author lc
 */
@SuppressWarnings("all")
public class Test {


    public static void main(String[] args) throws FileNotFoundException, IOException {
        String path = "E:\\workspace\\spring-boot-demo\\src\\main\\java\\com\\lc\\util\\config.properties";
		String data = getPropertyAbsolutely(path);
        System.out.println(data);

        String data2 = getPropertyRelative("/config.properties");
        System.out.println(data2);
    }

    /**
     * 相对路径获取
     * @param name
     * @return
     * @throws IOException
     */
    public static String getPropertyRelative(String name) throws IOException {
        String strKey = null;
        String strValue = null;
        Properties properties = new Properties();
        properties.load(Test.class.getResourceAsStream(name));
        Enumeration enum1 = properties.propertyNames();
        while (enum1.hasMoreElements()) {
             strKey = (String) enum1.nextElement();
             strValue = properties.getProperty(strKey);
        }
        return strKey+"="+strValue;
    }

    /**
     * 绝对路径获取
     * @param path
     * @return
     * @throws IOException
     */
    public static String getPropertyAbsolutely(String path) throws IOException {
        String strKey = null;
        String strValue = null;
        Properties properties = new Properties();
        properties.load(new FileInputStream(path));
        Enumeration enum1 = properties.propertyNames();
        while (enum1.hasMoreElements()) {
           strKey = (String) enum1.nextElement();
           strValue = properties.getProperty(strKey);
        }
        return strKey+"="+strValue;
    }
}

 注意:getResourceAsStream()入参不对会报空指针

eclipse是默认的getResourceAsStream()方法的路径是从/src下面开始的

而idea需要你新建一个标记为resources的文件夹,并放在该标记文件夹的下面即可

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值