Properties类,用于存取java配置文件,以键值对的形式存文件;
public class Properties extends Hashtable<Object,Object>,它是继承自Hashtable的;
实际使用:在项目中有一些值需要存储,但是又没有必要设计对应数据库,这时存文件的方式就可以很好的解决问题!
保存文字,文件内容如下:
/**
* 文件读写(键值对)工具类
*
* @author
*
*/
public class PropertiesFileUitl {
public static void main(String[] args) {
saveAndRead();
}
/**
* 存文件和读取文件
*/
private static void saveAndRead() {
// 获取项目部署目录
// String path = request.getServletContext().getRealPath("WEB-INF") + File.separator + fileName;
String path = "D://properties.txt";
// 存文件
// public class Properties extends Hashtable<Object,Object>
// Properties类,用于读取java配置文件, 表示了一个持久的属性集。
Properties properties = new Properties();
properties.setProperty("name", "Peter.pan");
properties.setProperty("age", "26");
properties.setProperty("add", "Sichuan.chengdu");
save(properties, path);
// 读文件
Map<String, String> map = read(path);
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
/**
* 使用properties保存文本到文件中(键值对)
*/
public static void save(Properties properties, String filePath) {
try {
OutputStream outputStream = new FileOutputStream(new File(filePath)); // 将键值内容保存至指定文件
properties.store(outputStream, "temp_info");
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取指定文件的内容(键值对)
*
* @param filePath
* @return
*/
public static Map<String, String> read(String filePath) {
Map<String, String> map = new HashMap<String, String>();
try {
Properties prop = new Properties(); // 从文件中获取信息
FileInputStream fis = new FileInputStream(new File(filePath));
prop.load(fis); // 加载文件流的属性
Enumeration<?> keys = prop.propertyNames(); // 返回属性列表中所有键的枚举
while (keys.hasMoreElements()) { // 遍历枚举,获取键值信息
String key = (String) keys.nextElement();
String value = prop.getProperty(key);
map.put(key, value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}