您的位置:首页 > 编程语言 > Java开发

Java Properties文件的读取和修改保存

2013-03-23 12:43 417 查看
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在根包找资源文件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: