javase-io-210510-02
- IO+Properties 读取配置文件
读取配置文件
IO + Properties
Properties 是一个Map集合,key和value都是String类型
经常变的数据,可以单独写到一个文件中,让程序动态读取
那么我们就需要配置文件了,java规范中要求,属性的配置文件建议以 .properties 结尾,,但不是必须是
Demo01.java
package com.bgy02;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;
public class Demo01 {
public static void main(String[] args) throws IOException {
// 创建一个输入流
FileReader reader = new FileReader("sqlinfo.properties");
// 新建一个Map集合
Properties properties = new Properties();
// 调用Properties对象的load方法将文件中的数据加载到Map集合中
properties.load(reader);
// 通过key获得value
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
System.out.println(user);
System.out.println(password);
}
}
java.util.ResourceBundle
1、通过 ResourceBundle.getBundle() 静态方法来获取(ResourceBundle是一个抽象类),这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可
package com.bgy02;
import java.util.ResourceBundle;
public class Demo02 {
public static void main(String[] args) {
// 假如你是在非Web项目中使用,则一定要写资源文件的路径,也就是包路径必须存在。
// 如果是Web项目,不写包路径可以,此时将资源文件放在WEB-INF\classes\目录下就可以。
/*
在使用中遇到的最大的问题可能是配置文件的路径问题,如果配置文件入在当前类所在的包下,
那么需要使用包名限定,如:info.properties入在info包下,
则要使用info/info.properties(通过Properties来获取)或info/info(通过ResourceBundle来获取);
属性文件在src根目录下,则直接使用jdbc.properties或jdbc即可。
*/
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
System.out.println(rb.getString("user"));
System.out.println(rb.getString("url"));
ResourceBundle rb01 = ResourceBundle.getBundle("info/info");
System.out.println(rb01.getString("driver"));
}
}
2、从InputStream 中读取,获取 InputStream 的方法和上面一样