java流的修饰;一个输入流通向两个管道的错误;Properties.load(InputStream)

xiaoxiao2021-02-27  306

第一次写博客,写的不好请多多包含。

昨天在做从配置文件读取jdbc配置信息时用到流,写了第一个流想着测试一下,测试成功了,

然后就准备通过Properties类来获取配置信息,用Properties对象的的load()方法去将InputStream

引入到Properties中,运行测试发现抛出空指针异常,调试了一下发现相应的键值为空。就使试着

将重点抽取出来,形成一个新类。

import java.util.*; import java.io.*; import java.sql.*; public class TestManyStream{ public static void main(String args[]){ //将数据从配置文件读入 //先定义输入流//重要的一行代码 InputStream in = TestManyStream.class.getClassLoader().getResourceAsStream("jdbc.properties");//jdbc.properties是配置文件 InputStreamReader re = new InputStreamReader(in); BufferedReader buff = new BufferedReader(re); String line; Properties prop = new Properties(); try{ while((line=buff.readLine())!=null){ System.out.println(line); } prop.load(in); String driverName = prop.getProperty("driverName"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); System.out.println(url); }catch(IOException e){ e.printStackTrace(); } } }

jdbc.properties配置文件的内容

driverName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test username=root password=hi这样测试结果,会输出所有的文档的内容,但输出url的内容为null

InputStream in = TestManyStream.class.getClassLoader().getResourceAsStream("jdbc.properties"); InputStreamReader re = new InputStreamReader(in); BufferedReader buff = new BufferedReader(re); String line; Properties prop = new Properties(); try{ prop.load(in); String driverName = prop.getProperty("driverName"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); System.out.println(url); while((line=buff.readLine())!=null){ System.out.println(line); } }catch(IOException e){ e.printStackTrace(); } 这样测试结果将会只显示url的值,而不会读取配置文件的所有的信息。 总结:

一个流只能进入一个通道,如果想进入另外的通道必须重新创建

转载请注明原文地址: https://www.6miu.com/read-1929.html

最新回复(0)