java中Properties文件的读写操作(自动创建文件夹和文件)

来源:互联网 发布:mac虚拟机分辨率设置 编辑:程序博客网 时间:2024/06/05 21:56
/************************************************************************************************/// 静态资源文件路径// String folderPath ="/data/im_cursor";// String filePath = "/im_cursor.properties";String folderPath = "D:/datadata/im_cursor";String filePath = "/im_cursor.properties";/** * 读取属性文件中相应键的值 *  * @param key *            主键 * @return String */private String getKeyValue(String key) {// 如果文件夹不存在就创建File folder = new File(folderPath);if (!folder.exists() && !folder.isDirectory()) {System.out.println("//不存在");folder.mkdirs();}// 如果文件不存在就创建File file = new File(folderPath + filePath);if (!file.exists()) {try {file.createNewFile();} catch (IOException e) {e.printStackTrace();}}Properties props = new Properties();try {// 读取文件FileInputStream fis = new FileInputStream(folderPath + filePath);props.load(fis);} catch (IOException e) {e.printStackTrace();System.exit(-1);}return props.getProperty(key);}/** * 更新properties文件的键值对 如果该主键已经存在,更新该主键的值; 如果该主键不存在,则插件一对键值。 *  * @param keyname *            键名 * @param keyvalue *            键值 */private void updateProperties(String keyname, String keyvalue) {// 如果文件夹不存在就创建File folder = new File(folderPath);if (!folder.exists() && !folder.isDirectory()) {System.out.println("//不存在");folder.mkdirs();}// 如果文件不存在就创建File file = new File(folderPath + filePath);if (!file.exists()) {try {file.createNewFile();} catch (IOException e) {e.printStackTrace();}}Properties props = new Properties();try {// 读取文件FileInputStream fis = new FileInputStream(folderPath + filePath);props.load(fis);// 调用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。OutputStream fos = new FileOutputStream(folderPath + filePath);props.setProperty(keyname, keyvalue);// 以适合使用 load 方法加载到 Properties 表中的格式,// 将此 Properties 表中的属性列表(键和元素对)写入输出流props.store(fos, "Update '" + keyname + "' value");} catch (IOException e) {System.err.println("属性文件更新错误");}}

0 0
原创粉丝点击