java Properties類對配置檔案的操作
阿新 • • 發佈:2018-12-16
/** * ClassName: PropertiesDemo * @Description: Properties * properties可以用來做配置檔案 * * ResouceRundle 只讀 * Properties 可讀可寫 * @author cai * @date 2018年10月18日 */ public class PropertiesDemo { public static String version = ""; public static String username = ""; public static String password = ""; //靜態程式碼塊,只會執行一次 static { readConfig(); } /** * * @Description: 對屬性檔案操作 * @param @param version * @param @param username * @param @param password * @return void * @throws */ private static void writerConfig(String version,String username,String password) { Properties p = new Properties(); p.put("app.version", version); p.put("db.username", username); p.put("db.password", password); OutputStream out; try { out = new FileOutputStream("config.properties"); p.store(out, "update config"); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void readConfig() { Properties p = new Properties(); InputStream inStream; try { inStream = new FileInputStream("config.properties"); p.load(inStream); version = p.getProperty("app.version"); username = p.getProperty("db.username"); password = p.getProperty("db.password"); inStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { writerConfig("2","cai","2222"); //readConfig(); //此處呼叫可以用上面的靜態程式碼塊來代替 System.out.println(version); System.out.println(username); System.out.println(password); } }
#update config
#Fri Oct 19 11:58:34 CST 2018
db.password=2222
app.version=2
db.username=cai