在Java中*.properties文件是一种资源文件或者是属性文件,这个文件的信息是以键值对存储(key–value),一般通过Properties类编辑该文件信息。
public class Properties extends Hashtable<Object,Object>
读取属性文件信息:
public synchronized void load(Reader reader);
public synchronized void load(InputStream inStream);
保存文件信息—向属性文件写入信息
public void store(Writer writer, String comments); //comments是注释
public void store(OutputStream out, String comments);
1.设置属性 : public synchronized Object setProperty(String key, String value)
2. 取得属性 : public String getProperty(String key),如果没有指定的key则返回null
3. 取得属性 : public String getProperty(String key, String defaultValue),如果没有指定的key则返回默认值
读取文件信息:
import java.io.*;
import java.util.Properties;
//读取文件属性信息
public class Testproperties {
public static void main(String[] args) {
Properties properties=new Properties();
//通过文件属性读取内容
//加载属性文件中的内容--load
//第一种方法:文件路径用绝对路径
File file=new File("D:\\VScode\\code\\src\\CODE\\栈队列\\src\\Test.properties");
try {
FileReader fileReader=new FileReader(file);
properties.load(fileReader);
} catch (Exception e) {
e.printStackTrace();
}
//第二种方法:文件路径用classpath路径---加载classpath中的文件,因为properties文件被加载后在class文件中
InputStream inputStream=Testproperties.class.getClassLoader().getResourceAsStream("Test.properties");
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
//读取属性信息--getProperty
System.out.println(properties.getProperty("1"));//happy day!
System.out.println(properties.getProperty("5","believe")); //5 没有,默认为believe
//在getProperty里设置的value不会对properties对象产生影响
System.out.println(properties);
//{3=everything will be ok!, 2=come on!, 1=happy day!}
}
}
向文件写入信息:
import java.io.*;
import java.util.Properties;
public class Testproperties {
public static void main(String[] args) {
Properties properties=new Properties();
properties.setProperty("1","hello sun");
properties.setProperty("2","hello tree");
File file=new File("D:\\VScode\\code\\src\\CODE\\栈队列\\src\\Test2.properties");
try {
FileWriter fileWriter=new FileWriter(file);
properties.store(fileWriter,"将信息写入属性文件");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(properties); //{2=hello tree, 1=hello sun}
}
}