本文共 1182 字,大约阅读时间需要 3 分钟。
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();/** 用程序对properties做修改,先将properties加载到内存中*/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流会占用系统资源,所以用完后需要关闭所有流,否则会浪费系统资源
说明:user.properties位于工程目录下。 步骤:先加载,再修改,后保存。最新内容请见作者的GitHub页:转载地址:http://cxiyl.baihongyu.com/