日期:2014-05-20  浏览次数:20911 次

利用Properties类从text文件读取中文是乱码
我有一个text文件,格式如下:
000001 中文名1
000002 中文名2
... ...

利用Properties类,load之后读取,结果中文都是乱码或者问号,请问这个该如何解决?
text文件另存为UTF-8或者其他格式都无效。读出的字符串也试过了各种编码和解码都不能解决。

------解决方案--------------------
使用 JDK 中的 native2ascii 工具转一下就可以了,以后使用“新文件”,
老文件需要保留着,便于以后更改,更改之后重新生成一下就可以了,建议
可以做个 bat 文件。

native2ascii <源文件> <新文件>
------解决方案--------------------
Properties 默认是按ISO-8859-1读取的,除了1楼的方法,还可以像下面这样,看你的Properties干什么用了,不同的需要可能需要的不一样。
/**
* 将ISO-8859-1转化为GBK

* @param para
* @return
*/
public static String isoToGbk(String para) {
try {
return new String(para.getBytes("ISO-8859-1"), "GBK");
} catch (UnsupportedEncodingException e) {
return "";
} catch (Exception e) {
return "";
}
}
------解决方案--------------------
你是从txt文件读还是名字是text的Properties文件啊
要是txt文件不如直接读呢那样就没问题了
------解决方案--------------------
native2ascii会不行?
这样试试,自己用输入输出流控制
Properties p = new Properties();
InputStreamReader isr = new InputStreamReader(new FileInputStream("your_property_file"), "UTF-8"); //用utf-8流读入文件
int len = 1048;
char[] buf = new char[len];
PipedOutputStream pos = new PipedOutputStream();//输出管道
PrintStream ps = new PrintStream(pos, false, "UTF-8");//输出流PipedInputStream pis = new PipedInputStream(pos); //输入管道
while (irs.read(buf, 0, len) != -1) {
ps.print(buf); //把读入文件输出到管道,从而得到新的管道输入流
}
ps.flash();
p.load(pis); //用新的管道输入流载入property

具体行不行不知道,试试看吧

------解决方案--------------------
比如

encode.bat


BatchFile code

set path=%path%;C:\jdk1.5\bin




native2ascii -encoding gb2312  ApplicationResources_temp.properties ApplicationResources_zh_CN.properties

native2ascii -encoding gb2312  displaytag_temp.properties displaytag_zh_CN.properties

native2ascii -encoding gb2312  eduadminResources_temp.properties eduadminResources_zh_CN.properties

native2ascii -encoding gb2312  studentResources_temp.properties studentResources_zh_CN.properties

------解决方案--------------------
改改Properties类

public synchronized void load(InputStream inStream) throws IOException {

BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "8859_1"));

改成
public synchronized void load(InputStream inStream) throws IOException {

BufferedReader in = new BufferedReader(new InputStreamReader(inStream, "GBK"));
------解决方案--------------------
是text文件,用Properties类是因为方便而且效率高。 
text文件格式就是我前面说的,上千行: 

00001 中文名1 
00002 中文名2 
.... 

如果直接读,请问怎么效率高一些
_____________________

不同问题,不同分析,你要把这些读到什么地方,用这些做什么?
------解决方案--------------------
第一步:
native2ascii.exe -encoding utf-8 .\src\Movision\Resource.properties .\classes\Movision\Resource.properties
(注意:properties文本用GB2312编码)
第二步:
public static void init() {
if (resources == null) {
resources = ResourceBundle.getBundle(sResourcesName);
}
}

/**
* @param sKeyName 被读取的Key=Value对
* @return 返回sKeyName对应的值
*/
public static String getString(String sKeyName) {
String sResult = null;
try {
init();