java 获取 resources 下面 properties文件内容

在Java项目中,通常会将properties文件放在src/main/resources目录下,以便它们能够被打包进最终的jar或war文件中,并且能够通过类路径(classpath)访问。要从类路径中加载properties文件,可以使用Class.getResourceAsStream()ClassLoader.getResourceAsStream()方法。以下是使用这两种方法之一来加载并读取resources目录下的config.properties文件内容的示例:

使用Class.getResourceAsStream()

如果你在某个类中执行此操作,可以直接使用当前类的类加载器:

import java.io.InputStream;
import java.util.Properties;

public class PropertiesFromResourcesExample {

    public static void main(String[] args) {
        // 获取config.properties文件的输入流
        InputStream inputStream = PropertiesFromResourcesExample.class.getResourceAsStream("/config.properties");
        
        if (inputStream != null) {
            Properties prop = new Properties();
            try {
                // 加载properties文件
                prop.load(inputStream);
                
                // 读取并打印属性值
                String username = prop.getProperty("username");
                System.out.println("Username: " + username);
                
                // 记得关闭输入流
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.err.println("Unable to find config.properties on classpath.");
        }
    }
}

注意路径字符串前的斜杠/,这表示从类路径的根开始查找。如果没有这个斜杠,则路径被视为相对于调用类的位置。

使用ClassLoader.getResourceAsStream()

如果你更倾向于使用类加载器直接:

import java.io.InputStream;
import java.util.Properties;

public class PropertiesFromResourcesExample {

    public static void main(String[] args) {
        // 获取系统类加载器
        InputStream inputStream = PropertiesFromResourcesExample.class.getClassLoader().getResourceAsStream("config.properties");
        
        if (inputStream != null) {
            Properties prop = new Properties();
            try {
                // 加载properties文件
                prop.load(inputStream);
                
                // 读取并打印属性值
                String username = prop.getProperty("username");
                System.out.println("Username: " + username);
                
                // 关闭输入流
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.err.println("Unable to find config.properties on classpath.");
        }
    }
}

这里没有前导斜杠,因为getResourceAsStream()默认从类路径根开始搜索。两种方法都是有效的,可以根据具体情况选择使用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值