JavaSE_Properties
1.Properties类的作用。
Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
2.读取Properties文件。
public class Deam {
public static void main(String[] args) {
//创建Properties对象。
Properties properties = new Properties();
//获取读取文件输入流。
try (BufferedReader br = new BufferedReader(new FileReader("D:\\MyJava Code\\Deam\\city1.properties"))){
//调用load方法写入Properties对象中。
properties.load(br);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//将properties对象进行输出。
for (Entry<Object, Object> entry : properties.entrySet()) {
System.out.println("key = " + entry.getKey());
System.out.println("value = " + entry.getValue());
}
}
}
3.向Properties文件写入数据。
public class Deam {
public static void main(String[] args) {
//创建Properties对象,并给Properties对象赋值。
Properties properties = new Properties();
properties.put("0310","邯郸市");
properties.put("0311","石家庄");
properties.put("0312","保定市");
properties.put("0313","张家口");
properties.put("0571","杭州市");
properties.put("0573","嘉兴市");
properties.put("0577","温州市");
//创建输出流
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\city2.properties"))){
//写入文件中。
properties.store(out, "中国区号");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.主要类及其方法。
- 核心类:
Properties类 - 主要方法:
load(); 方法:读取properties文件中的内容。
store(); 方法:将Properties对象中的内容写入文件中。