目录
Properties类
1 使用传统的方法
public class Properties01 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));
String line = " ";
while ((line = br.readLine()) != null){
String[] split = line.split("=");
System.out.println(split[0]+"值是:"+split[1]);
}
br.close();
}
}
2 使用Properties类去实现
Properties的基本介绍
1. 使用 Properties类读文件
public class Properties02 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
//加载指定的配置文件
properties.load(new FileReader("src\\mysql.properties"));
//把 k-v 显示到指定的控制台
properties.list(System.out);
System.out.println("==========");
//根据key获取对应的值
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println("用户名="+user);
System.out.println("密码="+pwd);
}
}
2. 使用Properties类添加key-val到新文件
public class Properties03 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.setProperty("charset","utf-8");
//保存中文时是保存unicode码值
properties.setProperty("user", "汤姆");
properties.setProperty("pwd", "abc111");
properties.store(new FileOutputStream("src\\msyql2.properties"),null);
System.out.println("保存配置文件成功~");
}
}
3. 使用Properties类修改文件
public class Properties02 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
//加载指定的配置文件
properties.load(new FileReader("src\\mysql.properties"));
//把 k-v 显示到指定的控制台
properties.list(System.out);
System.out.println("==========");
//修改文件
properties.setProperty("user","Jay");
properties.setProperty("pwd","6666666");
properties.store(new FileWriter("src\\mysql.properties"),null);
//根据key获取对应的值
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println("用户名="+user);
System.out.println("密码="+pwd);
}
}