大家好,又见面了,我是你们的朋友全栈君。
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 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 keys = prop.keySet();
for (Object key : keys) {
Object value = prop.get(key);
System.out.println(key + “=” + value);
}
Set> entrys = prop.entrySet();
for (Map.Entry 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=
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/126581.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...