package com.hzk.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Enumeration; import java.util.Properties; public class PropertiesTools { public static void writeProperties(String filePath, String parameterName, String parameterValue) { Properties props = new Properties(); try { File f = new File(filePath); if (f.exists()) { InputStream fis = new FileInputStream(filePath); props.load(fis); fis.close(); } else { System.out.println(filePath); f.createNewFile(); } OutputStream fos = new FileOutputStream(filePath); props.setProperty(parameterName, parameterValue); props.store(fos, ""); fos.close(); } catch (IOException e) { e.printStackTrace(); } } public static Properties readProperties(String filePath) { Properties props = new Properties(); InputStream is; try { is = new FileInputStream(filePath); props.load(is); is.close(); return props; } catch (Exception e1) { e1.printStackTrace(); return null; } } /** * 写之前将编码转为iso-8859-1,.propertise的默认编码 * @param data * @return */ public static String iso2utf8(String data){ String result = ""; try { result = new String(data.getBytes("iso-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } /** * 读数据的时候转码为utf-8。便于读取 * @param data * @return */ public static String utf82iso(String data){ String result = null; try { result = new String(data.getBytes("utf-8"), "iso-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } public static void main(String[] args) { PropertiesTools.writeProperties("d:\datas.properties", utf82iso("name"), utf82iso("tom")); PropertiesTools.writeProperties("d:\datas.properties", utf82iso("好这口"),utf82iso("hzk")); PropertiesTools.writeProperties("d:\datas.properties", utf82iso("hk"),utf82iso("户口")); Properties props = PropertiesTools.readProperties("d:\datas.properties"); Enumeration en = props.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); String keyDecode = iso2utf8(key); String value =iso2utf8((String) props.getProperty(key)); System.out.println("key:"+keyDecode+" value:"+value); } } }
如上面代码所看到的。注意新建的properties文件的默认编码是iso-8859-1,所以想读写中文数据。都要转码,对于中文会显示成一下形式,见datas.properties:
#
#Sat Jun 14 15:38:10 CST 2014
hk=u00E6u0088u00B7u00E5u008Fu00A3
name=tom
u00E5u00A5u00BDu00E8u00BFu0099u00E5u008Fu00A3=hzk
假设在myeclipse中保存为utf-8形式,再次能够手动输入中文就能够,可是下次一经代码写入再打开又会变为iso-8859-1的乱码,非常是蛋疼,所以要看中文能够通过代码读取转为utf-8,或者只先存为utf-8格式,编辑中文,不要代码写入中文就能够