首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java读取跟保存property文件(可含中文)

2012-12-22 
java读取和保存property文件(可含中文)java读取.property文件可使用java.util.Properties类的load加载.pro

java读取和保存property文件(可含中文)

java读取.property文件可使用java.util.Properties类的load加载.property文件然后使用getProperty()方法获得对应的值。保存键值对到.property文件中可使用store()方法或save方法(已废弃)。下面是例子:

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.Date;import java.util.Map;import java.util.Properties;/** * @author zxw *  */public class GetSaveProp {// public void GetP() {// Properties props = new Properties();// try {// // 资源文件存放在类文件的根目录下。即是放在src下面。// props.load(getClass().getClassLoader().getResourceAsStream(// "GetProp.properties"));// // 当资源文件中有中文的时候可以采用下面的编码转化方法来读取。// // 或者使用native2ascii jin1.properties或者jin1.txt// // jin.properties将资源文件进行编码转化,// // 然后直接读取props.getProperty("name");// System.out.println(new String(props.getProperty("name").getBytes(// "ISO-8859-1"), "GBK"));// } catch (UnsupportedEncodingException e) {// // TODO Auto-generated catch block// e.printStackTrace();// } catch (IOException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }// }private void saveProperty() {// 保存文件Properties propertie = new Properties();String characterString = "1中国的";propertie.setProperty("character", characterString);propertie.setProperty("date", new Date().toString());String fileName = "savetest.properties";String description = "CharaterTest";try {FileOutputStream outputFile = new FileOutputStream(fileName);propertie.store(outputFile, description);// property类关键的store方法outputFile.close();// propertie.list(System.out);System.out.println("File was saved!");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException ioe) {ioe.printStackTrace();}}public static void main(String[] args) {new GetSaveProp().saveProperty();//save file// read from propertyProperties readProps = new Properties();FileInputStream inStream;try {inStream = new FileInputStream("savetest.properties");readProps.load(inStream);// read from fileinputStream// props.list(System.out);if (readProps.get("character") != null) {System.out.println("character="+ new String(readProps.getProperty("character").getBytes("ISO-8859-1"), "UTF-8"));System.out.println("character="+ new String(readProps.getProperty("character").getBytes("UTF-8"), "UTF-8"));} else {System.out.println(readProps.get("character"));}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}
?

?

?

?

property文件保存中文时myeclipse会报错,这时我们需要修改资源文件的编码格式。Windons---->Preferences---->Content Type------>Text----->JavaPropertiesFile,把其Default encoding改为“utf-8”,按“update”更新。

?

乱码解决:http://www.iteye.com/topic/179279

?

?

热点排行