Properties文件一般用於配置信息。主要的操作也是讀取。
而我的需求是:保存一個變量的值到文件。下次程序運行還要用到。當然可以用普通文件保存。
但想用properties保存這個值。
總結:
1.properties是一個hashtable,保存鍵值對。
2.properties從文件初始化它,並修改它的值不保存的話,對文件沒影響。它和文件沒關系。
3.properties可以保存為xml或者文本
代碼
package com.zk.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties; public class PropertiesUtil { private static Properties properties= new Properties(); /*properties文件名*/ private static final String PROPERTIES_FILE_NAME="ArticlePrimaryKey.properties"; /*鍵*/ private static final String KEY_LASTID="lastid"; /** * 初始化properties,即載入數據 */ private static void initProperties(){ try { InputStream ips = PropertiesUtil.class.getResourceAsStream(PROPERTIES_FILE_NAME); properties.load(ips); ips.close(); } catch (IOException e) { e.printStackTrace(); } } /**將數據載入properties,並返回"lastid"的值 * @return */ public static int getPrimaryKey(){ if(properties.isEmpty())//如果properties為空,則初始化一次。 initProperties(); return Integer.valueOf(properties.getProperty(KEY_LASTID)); //properties返回的值為String,轉為整數 } /**修改lastid的值,並保存 * @param id */ public static void saveLastKey(int id){ if(properties.isEmpty()) initProperties(); //修改值 properties.setProperty(KEY_LASTID, id+""); //保存文件 try { URL fileUrl = PropertiesUtil.class.getResource(PROPERTIES_FILE_NAME);//得到文件路徑 FileOutputStream fos = new FileOutputStream(new File(fileUrl.toURI())); properties.store(fos, "the primary key of article table"); fos.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println(getPrimaryKey()); saveLastKey(1); } }
ArticlePrimaryKey.properties
#the primary key of article table
lastid=500
備注:
1.properties文件要放在PropertiesUtil同一個包下。因為加載和寫入都用了PropertiesUtil的類路徑。保存的修改后文件將在工程bin下的PropertiesUtil包下看到。
2.如果想將文件放在根包下。 則文件流應為
PropertiesUtil.class.getClassLoader().getResource(PROPERTIES_FILE_NAME);
即讓classloader在根包找資源文件。
