Java读取ini文件和中文乱码问题解决

来源:互联网 发布:中美网络安全问题 编辑:程序博客网 时间:2024/05/21 17:57

提出问题:

初用properties,读取java properties文件的时候如果value是中文,会出现读取乱码的问题 。

问题分析:

最初认为是文件保存编码问题,于是进行编码的统一:

1)把MyEclipse中所有的文件编码都修改成UTF-8,问题仍然存在;

2)把内容复制到EditPlus进行UTF-8编码转换,问题仍然存在

3)上网搜索有人提议重写properties类或者用jdk自带的编码转换工具,非常麻烦而且不可取,Java的开发者可定会考虑到编码问题;最初的方法如下:

/*** 读取配置文件* @param filePath配置文件的路径*/public static Properties readFileByStream(String filePath){filePath = getRealPath(filePath);//获取文件的绝对路径/**定义变量*/FileInputStream fileInput = null;//读       Propertiesproper = new Properties();       try {fileInput = new FileInputStream(filePath);proper.load(fileInput);  } catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}      return proper;}

这个方法用的是字节流来读取文件,中文会乱码;

因为字节流是无法读取中文的,所以采取把FileInputStream转换成InputStreamReader用字符流来读取中文。代码如下:

/*** 读取配置文件* @param filePath文件的路径*/public static Properties readFileByReader(String filePath){/**定义变量*/InputStream inputStream = ConfigFile.class.getClass().getResourceAsStream(filePath);    Propertiesproper = new Properties();      try {    BufferedReader bf = new BufferedReader(new  InputStreamReader(inputStream));  proper.load(bf);  } catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}      return proper;}


不再乱码了

为了方便查看,贴出完整代码:

public class ConfigFile {public static final String configFile = "/config/path.ini";//配置文件的路径/** * 获取文件中的某一项的值 * @param key * @return */public static String getKey(String key){Properties proper = readFileByReader(configFile);return proper.getProperty(key);}/** * 字节流读取配置文件 * @param filePath */public static Properties readFileByStream(String filePath){filePath = getRealPath(filePath);/**定义变量*/FileInputStream fileInput = null; //读    Properties proper;         proper = new Properties();      try {fileInput = new FileInputStream(filePath);proper.load(fileInput);  } catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}      return proper;}/** * 字符流读取配置文件 * @param filePath */public static Properties readFileByReader(String filePath){/**定义变量*/InputStream inputStream = ConfigFile.class.getClass().getResourceAsStream(filePath);      Properties proper;         proper = new Properties();      try {    BufferedReader bf = new BufferedReader(new  InputStreamReader(inputStream));  proper.load(bf);  } catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}      return proper;}/** 获取类根路径 */public static String getClassRoot(){return ConfigFile.class.getResource("/").getPath().substring(1);}/** 获取相对路径的真实的路径 */public static String getRealPath(String path){if(path.charAt(0) == '/'){path = getClassRoot() + path.substring(1);}else if(path.charAt(1) != ':'){path = getClassRoot() + path;}return path;}/** * 测试 */public static void main(String[] args) {System.out.println(getKey("welcome_message"));System.exit(0);}}

0 0