1、Properties读文件已经修改文件
1.1Properties简介
(1)专门用于读写配置文件的集合类 配置文件的格式: 键=值 键=值 (2)注意:键值对不需要有空格,值不需要用引号一起来。默认类型是String。 (3)Properties的常见方法 load:加载配置文件的键值对到Properties对象. list:将数据显示到指定设备. getProperty(key):根据键获取值. setProperty(key,value):设置键值对到Properties对象. store:将Properties中的键值对存储到配置文件.在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码. http://tool.chinaz.com/tools/unicode.aspx unicode码查询工具.
1.2、应用案列 (1)使用Properties类完成对mysql.properties的读取.
public class Properties02 {
public static void main(String [] args) throws IOException {
Properties properties = new Properties();
properties.load(new FileReader("src\\mysql.properties"));
properties.list(System.out);
String ip = properties.getProperty("ip");
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println(ip);
System.out.println(user);
System.out.println(pwd);
}
}
(2)使用Properties类添加key-val 到新文件mysql2.properties中.
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Properties03 {
public static void main(String [] args) throws IOException {
Properties properties = new Properties();
properties.setProperty("charts","utf8");
properties.setProperty("user","小明");
properties.setProperty("pwd","admin");
properties.store(new FileOutputStream("src\\mysql2.properties"),"hello world");
System.out.println("保存配置文件成功~");
}
}
(3)使用Properties类完成对 mysql.properties的读取,并修改某个key-val.
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Properties03 {
public static void main(String [] args) throws IOException {
Properties properties = new Properties();
properties.setProperty("charts","utf8");
properties.setProperty("user","小明");
properties.setProperty("pwd","88888888");
properties.store(new FileOutputStream("src\\mysql2.properties"),"hello world");
System.out.println("保存配置文件成功~");
}
}
|