Java 读写键值对
Properties类(读入写出 键值对) 是Map子类 Map方法都能用
public static void main(String[] args) throws IOException {
//读出
Properties pro=new Properties();
FileInputStream fis = new FileInputStream("F:\\Demo.properties");
//FileReader fr=new FileReader("F:\\Demo.properties");
pro.load(fis);//读取键值对 pro.load(fr);
String str=pro.getProperty("name");//取值
fis.close(); //fr.close();
//写入
Properties pro=new Properties();//创建集合
pro.setProperty("name","lisi");//写入键值对
pro.setProperty("hobby","eat");
pro.setProperty("hobby","sleep");//替换值
String str=pro.getProperty("name");//取值
Set<String> set=pro.stringPropertyNames();//像keySet获取 键值集合
for(String key:set){//遍历
System.out.println(key+"..."+pro.getProperty(key));
}
FileOutputStream fos=new FileOutputStream("F:\\aaa.properties",true);
//FileWriter fw = new FileWriter("F:\\aaa.properties",true);
pro.store(fos, "person information"); //(文件路径,添加理由)
//pro.store(fw,"save data");
fos.close();//5,关闭流
}
//父类方法:
Properties prop = new Properties();
prop.put("CZBK001", "zhangsan");//添加映射关系
Set<Object> keys = prop.keySet();
for (Object key : keys) {
Object value = prop.get(key);
System.out.println(key + "=" + value);
}
Set<Map.Entry<Object,Object>> entrys = prop.entrySet();
for (Map.Entry<Object, Object> entry : entrys) {
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + "=" + value);
}
PrintWriter pw = new PrintWriter("d.txt");//打印流对象
prop.list(pw);
pw.close();//释放资源
Properties类 JDBC从文件读取信息
public static Connection getConn(){
Connection conn=null; //不是局部
Properties pro=new Properties();
try{
FileInputStream fis=new FileInputStream("src/pro.properties");
pro.load(fis); //相对路径 正斜杠
Class.forName(pro.getProperty("driverClass"));//点出try catch
String url=pro.getProperty("url");
String username=pro.getProperty("username");
String password=pro.getProperty("password");// 空
conn=DriverManager.getConnection(url, username, password);//点 add catch
}
catch (ClassNotFoundException e) {e.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
return conn;
}
src/pro.properties文件://无空格 密码空串(空格)
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/guanjiapo?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
username=root
password=