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格式,编辑中文,不要代码写入中文就可以
Properties类读写.properties配置文件,布布扣,bubuko.com
时间: 2024-10-24 07:16:12