JAVA读取属性文件含中文字符

package com.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
public class StudentDemo2 {

private Map<String,Object> objects = new HashMap<>();
public static void main(String[] args) throws Exception {
    new StudentDemo2().readFile("config.txt");
}


public static void test2() {
    StudentDemo2 sd2 = new StudentDemo2();
    try {
        Map<String,Object> myobjs = sd2.readFile("config.txt");
        Student stu = (Student) myobjs.get("student");
        stu.eat();
        Date now = (Date) myobjs.get("now");
        System.out.println(now);
    } catch (Exception e) {
        e.printStackTrace();
    }
}


public Map<String,Object> readFile(String fileName) throws Exception{
    Properties prop = new Properties();
    File file = new File(fileName);
    //FileReader reader = new FileReader(file);
    FileInputStream fis = new FileInputStream(file);
    prop.load(fis);//可以用字符流和字节流
    //根据key获取value
    String value = prop.getProperty("student");     
    System.out.println(value);
    //循环获取所有的key和value
    Set<Entry<Object, Object>> entrys= prop.entrySet();
    for(Entry<Object, Object> entry : entrys){
        System.out.println(entry.getKey()+"-->"+entry.getValue());
        String key=new String( entry.getKey().toString().getBytes("ISO8859-1"),"GBK");
        System.out.println(key+"-->"+entry.getValue());

        Class<?> clazz = Class.forName(entry.getValue().toString());
        Object obj = clazz.newInstance();

        objects.put(entry.getKey().toString(),obj);
    }
    return objects;
}

}

猜你喜欢

转载自blog.csdn.net/kongfanyu/article/details/52954585