properties是java文件特有的一种文件类型,该文件的信息以键-值的格式存放。通常可以将容易变换的一些系统参数写到properties文件中,然后利用java程序读取,这样可以提高程序的灵活性。
存贮格式
name=admin
password=admin
操作properties文件需要用到Properties类:Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。
常用方法:
读取资源文件所有的值:
/**
* 读取某一键的值
*
* @param filePath 资源文件路径
* @param key key
*/
public void readProperties(String filePath, String key)throws Exception {
Properties properties = new Properties();
try {
properties.load(this.getClass().getClassLoader().getResourceAsStream(filePath));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(unicode(key));
System.out.println(unicode(properties.getProperty(key)));
}
/**
* 读取资源文件所有的值
*
* @param filePath 资源文件路径
*/
public void readProperties(String filePath) {
Properties properties = new Properties();
try {
properties.load(this.getClass().getClassLoader().getResourceAsStream(filePath));
Enumeration enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
System.out.println("key:" + key);
System.out.println("value:" + properties.getProperty(key));
}
} catch (Exception e) {
e.printStackTrace();
}
}
写入资源文件
/**
* 写入资源文件
*
* @param fileName 文件名称
* @param key key
* @param value value
*/
public void writeProperties(String fileName, String key, String value) {
Properties properties = new Properties();
String path = this.getClass().getClassLoader().getResource("").getPath().substring(1);
path = path + File.separator + fileName;
File file = new File(path);
try {
InputStream inputStream = new FileInputStream(file);
properties.load(inputStream);
OutputStream outputStream = new FileOutputStream(file);
properties.setProperty(key, value);
properties.store(outputStream, key);
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
因为Properties在读取资源文件是使用的是ISO-8859-1的编码格式。所以有些字符:例如汉字,在读写时会出现乱码。这种情况下可以先转码。
/**
* 中文转Unicode
*
* @param str 中文字符串
* @return 编码后
*/
public String convert(String str) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
Character character = str.charAt(i);
unicode.append("\\"+"u"+Integer.toHexString(character));
}
return unicode.toString();
}
/**
* 将unicode转为中文
*
* @param unicode unicode
* @return 中文
* @throws Exception
*/
public String unicode(String unicode) {
try {
return new String(unicode.getBytes("UTF-8"),"UTF-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
注:资源文件需放在资源目录,例如src下面。
源码:
https://github.com/wolf521/demo/tree/master/src/main/java/com/example/demo/io