使用Java向properties存數(shù)據(jù)
package writeToProperties; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class WriteToProperties { public void addUser(String name,String password){ FileInputStream fis = null; Properties pro = new Properties(); /* * 用程序?qū)roperties做修改,先將properties加載到內(nèi)存中 */ try { fis = new FileInputStream("user.properties");//初始化輸入流 } catch (FileNotFoundException e) { e.printStackTrace(); } try { pro.load(fis); //加載 } catch (IOException e) { e.printStackTrace(); } pro.setProperty(name, password); //修改properties /* * 將改動后的properties寫回硬盤 */ FileOutputStream fos = null; try { fos = new FileOutputStream("user.properties"); //初始化一個輸出流 } catch (FileNotFoundException e) { e.printStackTrace(); } try { pro.store(fos,"#"); //寫回硬盤 } catch (IOException e) { e.printStackTrace(); } try { fis.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { WriteToProperties wtp = new WriteToProperties(); wtp.addUser("lucy", "123"); wtp.addUser("lily", "123"); } } |
注意:初始化IO流會占用系統(tǒng)資源,所以用完后需要關(guān)閉所有流,否則會浪費(fèi)系統(tǒng)資源
說明:user.properties位于工程目錄下。
步驟:先加載,再修改,后保存。