`

解决Java读取properties文件的中文问题的新办法(不使用native2ascii.exe及其他工具)

 
阅读更多

解决Java读取properties文件的中文问题的新办法(不使用native2ascii.exe及其他工具)



原理:转码
关键代码:new String(temp.getBytes("ISO-8859-1"), "GBK")
其实很简单,就是简单的转码,下面给出源代码(两个ReadProperties.java和LogSystem.properties)和使用方法:

ReadProperties.java

import java.util.Properties;
import java.io.UnsupportedEncodingException;
import java.io.FileInputStream;
import java.io.*;

public class ReadProperties {
private static Properties props = new Properties();
private static FileInputStream fis;
private static String propertiesName = "LogSystem.properties"; //需要读取的properties文件名,默认当前目录下

private static void InitializationProperties() {
try {
fis = new FileInputStream(propertiesName);
props.load(fis);
fis.close();
} catch (FileNotFoundException ex) {
System.out.println("logsystem.tools.ReadProperties :系统找不到文件->" +
propertiesName);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ex1) {
ex1.printStackTrace();
}
}
}
}


/**
* 根据配置项获取配置值
* 可以兼容GBK编码,支持中文
* @param key String -- 配置项
* @return String -- 配置值
*/
public static String getPropertyByKey(String key) {
InitializationProperties();
String temp = props.getProperty(key);
String sp = "";
if (temp != null) {
try {
sp = new String(temp.getBytes("ISO-8859-1"), "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
props.clear();
return sp;
}


public static void main(String[] args) {

System.out.println(ReadProperties.getPropertyByKey("clientlogfilename"));//使用方法,很简单吧?
}
}

clientlogfilename=我不是一个人

控制台打印:

我不是一个人

希望对大家能有所帮助!


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics