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

来源:互联网 发布:网络主播妆容视频教程 编辑:程序博客网 时间:2024/05/22 17:08

关于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放在不同的位置去试一下,空指针一般就是文件的路径问题,把路径弄明白了,在平时的项目中才能运用自如,好啦,今天就分享到这里吧。

阅读全文
0 0