properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,是一种以key-value形式存储信息的文件。因为配置文件需要在整个系统中保持一致性,所以经常和单例模式配合使用。
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Properties;
public final class Test {
private static final Properties apProp__;
// 单例模式
private Test(){}
// 静态初始化块
static{
String propertiesPath = "c://test.properties";
apProp__ = new Properties();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(propertiesPath));
apProp__.load(br);
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
if (br != null) {
try {
br.close();
} catch (Exception ex) { }
}
}
}
public String getProperty(String key){
return apProp__.getProperty(key);
}
}
test.properties文件内容:
path = c://test.txt
这样其他类如果想用c://test.txt这个路径的话,可以调用Test.getProperty("path")就可以了
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Properties;
public final class Test {
private static final Properties apProp__;
// 单例模式
private Test(){}
// 静态初始化块
static{
String propertiesPath = "c://test.properties";
apProp__ = new Properties();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(propertiesPath));
apProp__.load(br);
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
if (br != null) {
try {
br.close();
} catch (Exception ex) { }
}
}
}
public String getProperty(String key){
return apProp__.getProperty(key);
}
}
test.properties文件内容:
path = c://test.txt
这样其他类如果想用c://test.txt这个路径的话,可以调用Test.getProperty("path")就可以了