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=\u00E6\u0088\u00B7\u00E5\u008F\u00A3
name=tom
\u00E5\u00A5\u00BD\u00E8\u00BF\u0099\u00E5\u008F\u00A3=hzk
如果在myeclipse中保存為utf-8形式,再次可以手動輸入中文就可以,但是下次一經代碼寫入再打開又會變為iso-8859-1的亂碼,很是蛋疼,所以要看中文可以通過代碼讀取轉為utf-8,或者僅僅先存為utf-8格式,編輯中文,不要代碼寫入中文就可以