public class Test {
public static void main(String[] args) {
/*测试读取properties文件
* OperateProperties op=new OperateProperties();
op.readProperties("f:/test.properties");
Map map=op.processProperties();
Set keys=map.keySet();
String key=null;
for(Object k:keys){
key=k+"";
System.out.println(" "+key+" "+map.get(key));
}*/
/* 写入一个新的properties文件,save方法会把中文转换成unicode编码,不会出现中文乱码
OperateProperties op2=new OperateProperties();
op2.writeProperties("f:/testSave.properties");*/
/*
* 使用list方法写入一个properties文件,不会出现中文乱码,不会转换成unicode编码,正常显示中文
* OperateProperties opx=new OperateProperties();
opx.writeProperties(new File("f:/testList.properties"));*/
//写入一个properties文 件,store()方法,也会把中文转换成unicode编码,不会出现乱码,推荐使用store()
OperateProperties op2=new OperateProperties();
op2.writeProperties("f:/testStore.properties");
}
}
public class OperateProperties {
private static Properties prop;
static{
prop=new Properties();
}
/**
* 读取properties文件
*
* @param fileName
*/
void readProperties(String fileName){
FileInputStream is=null;
try{
// BufferedInputStream bis=null;
is=new FileInputStream(fileName); // 字节流容易出现中文乱码
// bis=new BufferedInputStream(is);
prop.load(is);
// prop.load(bis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 把properties的值存储到Map
* @return Map
*/
Map processProperties(){
Map map=new Hashtable();
Set keys=prop.keySet();
String key=null;
String str="";
for(Object k:keys){
key=k+"";
map.put(key, prop.getProperty(key));
str=prop.getProperty(key);
}
return map;
}
// 解决中文乱码的方法(读):使用jdk/bin下的native2ascii命令把中文转换成unicode编码
/**
* 写入Properties文件,会覆盖以前的内容
* @param fileName 为properties文件
*/
void writeProperties(String fileName){
FileOutputStream fos=null;
try{
File file=new File(fileName);
if(!file.exists()){
file.createNewFile();
}
fos=new FileOutputStream(file);
prop.setProperty("what.is.you.name", "wangwu");
prop.setProperty("your.sex", "男");
// prop.save(fos, "注释"); //写入的中文“注释”为乱码,但是属性值,如果是中文 会转换成unicode,不会出现乱码,推荐使用
prop.store(fos, "我是一只小鸟");
//prop.storeToXML(fos, "comment"); // 属性值如果是中文,会出现中文乱码,不推荐使用
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
finally{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 写入一个properties文件,会覆盖以前的内容
* 正常显示中文 ,不会把中文转换成unicode
* @param file
*/
void writeProperties(File file){
PrintStream ps=null;
try{
if(!file.exists()){
file.createNewFile();
}
ps=new PrintStream(file);
prop.setProperty("what.is.you.name", "wangwu");
prop.setProperty("your.sex", "男");
prop.list(ps);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
finally{
ps.close();
}
}
}