Hashtable和HashMap的主要区别
-
主要:Hashtable线程安全,同步,效率相对低下
HashMap线程不安全,非同步,效率相对 - 父类:Hashtable是Dictionary, HashMap是AbstractMap
- null:Hashtable键与值不能为null , HashMap键最多一个null,值可以多个null
Properties
- 作用:读取资源配置文件
- 键与值只能为字符串
- 方法:
-
-
getProperty(String key)
getProperty(String key, String defaultValue)
setProperty(String key, String value)
-
后缀:.properties
-
-
store(OutputStream out, String comments)
将此属性列表(键和元素对)写入此
Properties
表中,以适合于使用load(InputStream)
方法加载到Properties
表中的格式输出流。store(Writer writer, String comments)
将此属性列表(键和元素对)写入此
Properties
表中,以适合使用load(Reader)
方法的格式输出到输出字符流。load(InputStream inStream)
从输入字节流读取属性列表(键和元素对)。
load(Reader reader)
以简单的线性格式从输入字符流读取属性列表(关键字和元素对)。
-
.xml
-
-
storeToXML(OutputStream os, String comment)
发出表示此表中包含的所有属性的XML文档。
storeToXML(OutputStream os, String comment, String encoding)
使用指定的编码发出表示此表中包含的所有属性的XML文档。
loadFromXML(InputStream in)
将指定输入流中的XML文档表示的所有属性加载到此属性表中。
-
相对路径与绝对路径
- 绝对路径: 盘符:/
相对路径:当前项目、工程
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
* properties资源配置文件的读写
* key 与value只能为字符串
*/
public class Properties1{
public static void main(String[] args) throws FileNotFoundException , IOException {
Properties pro=new Properties();
pro.setProperty("driver","oracle.jdbc.driver.OracleDriver");
pro.setProperty("url","jdbc:oracle:thin:localhost:1521:orcl");
pro.setProperty("user","zhang");
pro.setProperty("pwd","rui");
//存储到D:/java 绝对路径
pro.store(new FileOutputStream(new File("D:/java/db.properties")),"db配置");
pro.storeToXML(new FileOutputStream(new File("D:/java/db.xml")),"db配置");
//使用相对路径 当前的工程
pro.store(new FileOutputStream(new File("src/db.properties")),"db配置");
}
}
import java.io.*;
import java.util.Properties;
/**
* properties资源配置文件的读写
* key 与value只能为字符串
*/
public class Properties1{
public static void main(String[] args) throws FileNotFoundException , IOException {
Properties pro=new Properties();
//读取绝对路径
// pro.load(new FileReader("D:/java/db.properties"));
//读取相对路径
pro.load(new FileReader("src/db.properties"));
System.out.println(pro.getProperty("user","zhangrui"));
}
}
四、类路径加载资源文件
-
类.class.getResourceAsStream("/")
-
Thread.currentThread().getContextClassLoader().getResourceAsStream("")
public class Properties1{ public static void main(String[] args) throws FileNotFoundException , IOException { Properties pro=new Properties(); pro.load(Properties1.class.getResourceAsStream("/com/zhang/db.properties")); pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/zhang/db.properties")); System.out.println(pro.getProperty("user","zhangrui")); } }