获取资源文件的数据Properties

本文介绍了一个Java示例程序,演示如何从类路径下加载配置文件并读取属性值。通过不同的路径指定方式对比,说明正确的资源文件加载方法,并展示了错误路径设置导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

public class SpringClassTest {

// ip=192.168.0.1
// port=8080

public SpringClassTest() {
super();
}

public void read() throws IOException {
Properties p = new Properties();

System.out.println("this.getClass():" + this.getClass()
+ "\nthis.getClass().getClassLoader():"
+ this.getClass().getClassLoader().toString());

InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("ipConfig.properties");

p.load(inputStream);

inputStream.close();

System.out.println("ip:" + p.getProperty("ip") + ",port:"
+ p.getProperty("port"));

}

public static void main(String[] args) throws IOException {
new SpringClassTest().read();
}

}


配置文件:
ipConfig.properties
ip=192.168.0.1
port=8080


结果:
this.getClass():class com.kettas.spring.test.SpringClassTest
this.getClass().getClassLoader():sun.misc.Launcher$AppClassLoader@19821f
ip:192.168.0.1 ,port:8080


2中错误写法:
[list]
[*]第一种加上了“/”---->/ipConfig.properties
[/list]
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("/ipConfig.properties");


[list]
[*]第二种是写据对路径--->D:\\Workspaces\\MyEclipse 6.5\\components\\src\\com\\spring\\test\\ipConfig.properties
[/list]

InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("D:\\Workspaces\\MyEclipse 6.5\\components\\src\\com\\spring\\test\\ipConfig.properties");


以上2中写法都会抛
[color=red]Exception in thread "main" java.lang.NullPointerException[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值