Properties
继承自Hashtable,主要用于处理属性文件
public class TestProperties {
public static void main(String[] args) throws IOException {
Properties properties=new Properties();
properties.load(TestProperties.class.getClassLoader().getResourceAsStream("user.properties"));
String username = properties.getProperty("username");
System.out.println("username = " + username);
String password = properties.getProperty("password");
System.out.println("password = " + password);
}
}
另一种读取属性文件的处理方式
public class TestResourceBundle {
public static void main(String[] args) {
//只写文件名,不写扩展名
ResourceBundle bundle=ResourceBundle.getBundle("config/user");
String username = bundle.getString("username");
System.out.println("username = " + username);
String password = bundle.getString("password");
System.out.println("password = " + password);
}
}
-
配置文件,资源文件以 .properties 作为扩展名
- username = root
- password = 123456
-
db.properties 文件来配置文件
#key=value uname=root pwd=123
-
具体操作
Properties properties = new Properties(); FileInputStream in = new FileInputStream("D:\\javase\\homework\\practice\\day21\\src\\cn\\sycoder\\PropertiesDemo\\db.properties"); properties.load(in); System.out.println(properties); System.out.println(properties.get("username")); System.out.println(properties.get("password"));
-
ClassLoader类加载器去读
className.class.getClassLoader().getResource(“”).toString()+CONF_FILE
-
使用绝对路径
//使用绝对路径 Properties properties = new Properties(); FileInputStream in = new FileInputStream(path); properties.load(in); System.out.println(properties);
-
使用相对路径从根目录开始找
Properties properties = new Properties(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream resourceAsStream = classLoader.getResourceAsStream(path); properties.load(resourceAsStream); System.out.println(properties);
-
使用相对路径(相对于我们使用的类的文件夹开始)
Properties properties = new Properties(); InputStream inputStream = Test.class.getResourceAsStream(path); properties.load(inputStream); System.out.println(properties);
-