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= 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM