作者:红昊子楽楽七_358 | 来源:互联网 | 2024-11-11 13:55
属性类`Properties`是`Hashtable`类的子类,用于存储键值对形式的数据。该类在Java中广泛应用于配置文件的读取与写入,支持字符串类型的键和值。通过`Properties`类,开发者可以方便地进行配置信息的管理,确保应用程序的灵活性和可维护性。此外,`Properties`类还提供了加载和保存属性文件的方法,使其在实际开发中具有较高的实用价值。
属性类 Properties
Properties 类本身是 HashTable 类的子类,数据存放也是按照key和value的形式存放数据的。
public class Properties extends HashTable<Object, Object>
Properties 类的主要方法&#xff1a;
- public Properties() //构造一个空的属性类
- public Properties(Properties defaults) //构造一个指定属性内容的类
- public String getProperty(String key) //根据属性的key取得属性的value&#xff0c;如果没有key则返回null
- public String getProperty(String key, String defaultValue) //根据属性的key取得属性的value&#xff0c;如果没有key&#xff0c;则返回defaultValue
- public Object setProperty(String key, String value) //设置属性
- public void list(PrintStream ouot) //属性打印
- public void load(InputStream inStream) throws IOException //从输入流中取出全部的属性内容
- public void loadFormXML(InputStream in) throws IOException, InvalidPropertiesFormatException //从XML文件格式中读取内容
- public void store(OutputStream os, String comment) throws IOException //将属性内容通过输出流输出&#xff0c;同时声明属性的注释
- public void storeToXML(OutputStream os, String comment) throws IOException //以XML文件格式输出属性&#xff0c;默认编码
- public void storeToXML(OutputStream os, String comment, String encoding) throws IOException //以XML文件格式输出&#xff0c;用户指定默认编码
import java.io.*;
import java.util.Properties;/*** Created by Javen on 2018/8/24.*/
public class PropertiesDemo {public static void main(String args[]) {writePropertiesFile(); readPropertiesFile(); }public static void writePropertiesFile() {File file &#61; new File("D:" &#43; File.separator &#43; "PropertiesDemoWrite.txt");File file2 &#61; new File("D:" &#43; File.separator &#43; "PropertiesDemoWriteXml.txt");Properties properties &#61; new Properties();properties.setProperty("javen", "19950601");properties.setProperty("nanshen", "19960101");properties.setProperty("kunshen", "19940101");properties.setProperty("zuqiang", "19940201");try {properties.store(new FileOutputStream(file), "PropertiesDemo");properties.storeToXML(new FileOutputStream(file2), "PropertiesDemoXml", "utf-8");} catch (IOException e) {e.printStackTrace();}}public static void readPropertiesFile() {File file &#61; new File("D:" &#43; File.separator &#43; "PropertiesDemoWrite.txt");File file2 &#61; new File("D:" &#43; File.separator &#43; "PropertiesDemoWriteXml.txt");Properties properties &#61; new Properties();Properties properties2 &#61; new Properties();try {properties.load(new FileInputStream(file));properties2.loadFromXML(new FileInputStream(file2));} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}String jw &#61; properties.getProperty("javen");String ns &#61; properties.getProperty("nanshen");String zq &#61; properties.getProperty("gangge");String ks &#61; properties.getProperty("kunshen");System.out.println( jw &#43; "\n" &#43; ns &#43; "\n" &#43; zq &#43; "\n" &#43; ks);}
}