简介
属性文件指的是项目中专门用来存放项目配置信息的文件,其后缀一般为.properties
。 属性文件也叫资源配置文件
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
Writer writer = new FileWriter(new File("E:/abc.propertiest"));
properties.setProperty("url","jdbc:mysql:///db_test");
properties.setProperty("user","root");
properties.setProperty("pasword","root");
properties.store(writer, "haha");
writer.close();
}
示例:读属性文件
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
Reader reader = new FileReader(new File("E:/abc.propertiest"));
properties.load(reader);
String url = properties.getProperty("url");
System.out.println(url);
String user = properties.getProperty("user2");
System.out.println(user);
String password = properties.getProperty("password2","default");
System.out.println(password);
}
示例:java Web项目中读取Properties 文件(★★★★★)
static {
Properties properties = new Properties();
InputStream is =类名.class.getResourceAsStream("/abc.properties"));
properties.load(is);
String url = properties.getProperty("url");
System.out.println(url);
String user = properties.getProperty("user2");
System.out.println(user);
String password = properties.getProperty("password2","default");
System.out.println(password);
}
注意:这种方式除了可以在JavaWEB中使用,也可以在JavaSE中使用,实际开发时建议使用这种方式。
ResourceBundle读取配置文件第一步:在resources/目录下创建属性文件mysql.properties:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_test?useSSL=false&serverTimezone=UTC
username=root
password=root
第二步:编写读取属性的工具类:
public class PropertiesUtil {
private static Map valueMap = new HashMap();
static {
// 国际化
ResourceBundle ct = ResourceBundle.getBundle("mysql"); //注意此处,只需文件名而不需要文件后缀
Enumeration enums = ct.getKeys();
while ( enums.hasMoreElements() ) {
String key = enums.nextElement();
String value = ct.getString(key);
valueMap.put(key, value);
}
}
public static String getValue(String key ) {
return valueMap.get(key);
}
}
测试代码:
public static void main(String[] args) {
System.out.println(PropertiesUtil.getValue("driver"));
}