关于properties空指针报错的问题 java.lang.NullPointerException

关于properties空指针报错的问题

java.lang.NullPointerException

这里写图片描述


首先我们来说一下通过properties对象获取资源文件中的数据简单的几个步骤

一.需要建一个资源文件JDBC.properties放在src文件夹中
文件中的键值对:
这里写图片描述
文件放的位置:
这里写图片描述
二.需要创建一个properties的对象,
三.通过获取输入流

1.通过FileInputStream获取流
2.通过类加载器来获取流
类名.class.getClassLoader().getResourceAsStream("文件路径")
3.通过字节码文件直接获取流
类名.class.getResourceAsStream("文件路径")
4.通过获取当前的线程来获取流{推荐使用这种方法,可以解决掉硬解码问题}
Thread.currentThread().getResourceAsStream("文件路径")

四.使用properties对象.load(流)来读取文件
五.使用properties对象.getProperty(key)来获取数据
代码如下:
main方法{
ByFileInputStream();//第一种获取流的方式
ByGetClassLoad();//第二种获取流的方式
ByGetResourceAsStream();//第三种获取流的方式
//第四种获取流的方式
Properties pro = new Properties();
ClassLoader loder = Thread.currentThread().getContextClassLoader();
InputStream ips = loder.getResourceAsStream(“JDBC.properties”);
pro.load(ips);
System.out.println(pro.getProperty(“username”));
}

public static void ByGetResourceAsStream() throws IOException {
Properties pro = new Properties();
InputStream ras=TextProperties.class.getResourceAsStream(“../JDBC.properties”); pro.load(ras);
System.out.println(pro.getProperty(“username”));
}

public static void ByGetClassLoad() throws IOException {
Properties pro = new Properties();
ClassLoader classLoader =TextProperties.class.getClassLoader();
InputStream inputStream=classLoader.getResourceAsStream(“JDBC.properties”);
pro.load(inputStream);
System.out.println(pro.getProperty(“password”));
}
public static void ByFileInputStream() throws FileNotFoundException, IOException {
Properties pro = new Properties();
FileInputStream fis = new FileInputStream(“src/JDBC.properties”);//相对路径
pro.load(fis);
System.out.println(pro.getProperty(“username”,”1”));//没有找到username 则输入1;
}
}
最后的输入结果为
这里写图片描述
最后各位可以把JDBC放在不同的位置去试一下,空指针一般就是文件的路径问题,把路径弄明白了,在平时的项目中才能运用自如,好啦,今天就分享到这里吧。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值