Java读取文件中含有中文的解决办法

在Eclipse中运行时一直都很正常,但是一旦导出成jar包时就出现错误,不能正确读取中文,试了很多办法都没有用。 什么new String(str.getBytes(), "UTF-8"); 和System.setProperty("file.encoding","UTF-8")都不顶用。
最后发现只要在读取文件内容的时候,把InputStreamReader写成下面这样即可。
InputStreamReader  read = new InputStreamReader(new FileInputStream(f),"UTF-8");

BufferedReader reader=new BufferedReader(read);
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}


通过打开文件是指定文件编码的方法把这个问题轻松的解决了。

最后总结一下:java要读取数据流的时候一定要指定数据流的编码方式(至少读取String流的时候要这么作。

输出文件内容时,转换一下成UTF-8编码,转换方式为:

    /**
* 中文转unicode
*
* @param str
* @return 反回unicode编码
*/
public static String chineseToUnicode(String str)
{
String result = "";
for (int i = 0; i < str.length(); i++)
{
int chr1 = (char)str.charAt(i);
if(chr1 > 0 && chr1 < 11 * 15)
{
result += str.charAt(i);
}
else if (chr1 <= 0 || chr1 >= 16 * 16 * 16)
{
result += "\\u" + Integer.toHexString(chr1);
}
else if (chr1 < 16 * 16 * 16 && chr1 >= 16 * 16)
{
result += "\\u0" + Integer.toHexString(chr1);
}
else if (chr1 < 16 * 16 && chr1 >= 11 * 15)
{
result += "\\u00" + Integer.toHexString(chr1);
}
}
return result;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值