關於Java中的*.properties的操作
阿新 • • 發佈:2019-02-13
只給出具體程式碼,覺得有用的可以參考一下
/** * 流處理工具類 * @author Shmily */ public class StreamUtils { private static Logger logger = Logger.getLogger(StreamUtils.class); /** * 將配置檔案*。properties直接轉換為Java物件 * @param proPath 配置檔案路徑 * @return java.util.Properties or null */ public static Properties loadProperty(String proPath){ Properties temp=new Properties(); InputStream in= StreamUtils.class.getResourceAsStream(proPath); try { temp.load(in); in.close(); return temp; } catch (Exception e) { logger.warn("檔案載入失敗"); return null; } } /** * 修改屬性檔案的值 * @param proPath 屬性檔案的路徑 * @param key * @param value * @return 是否修改成功 */ public static boolean updateProperty(String proPath,String key,String value){ Properties temp=loadProperty(proPath); if(temp!=null){ //修改值 temp.setProperty(key, value); try { File f=new File(String.class.getResource(proPath).toURI().getPath()); OutputStream out=new FileOutputStream(f); //儲存更新 temp.store(out, "update"); f=null; out.flush(); out.close(); } catch (Exception e) { logger.error("屬性更新失敗"); } return true; }else{ logger.error("檔案載入失敗"); return false; } } /** * 刪除特定key * @param proPath 屬性檔案的路徑 * @param key * @return 是否刪除成功 */ public static boolean updateProperty(String proPath,String key){ Properties temp=loadProperty(proPath); if(temp!=null){ temp.remove(key); try { FileOutputStream out=new FileOutputStream(new File(String.class.getResource(proPath).toURI().getPath())); //儲存更新 temp.store(out, "update"); temp=null; out.flush(); out.close(); } catch (Exception e) { logger.error("屬性更新失敗"); } return true; }else{ logger.error("檔案載入失敗"); return false; } } }