Android:如何读取包含汉字的txt文件? [英] Android: How to read a txt file which contains Chinese characters?

查看:201
本文介绍了Android:如何读取包含汉字的txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多汉字的txt文件,该txt文件位于res / raw / test.txt目录中。我想读取文件,但是不知何故我无法正确显示汉字。这是我的代码:

i have a txt file which contains many chinese characters, and the txt file is in the directory res/raw/test.txt. I want to read the file but somehow i can't make the chinese characters display correctly. Here is my code:

try {
    InputStream inputstream = getResources().openRawResource(R.raw.test);
    BufferedReader bReader = new BufferedReader(
        new InputStreamReader(inputstream,Charset.forName("UTF-8")));
    String line = null;
    while ((line= bReader.readLine())!= null) {
        Log.i("lolo", line);
        System.out.println("here is some chinese character 这是一些中文字");
    }
} catch (IOException e) {
    e.printStackTrace();
}

Log.i( lolo,line);和System.out.println(这是一些中文字)无法正确显示字符,我什至在println()方法中也看不到中文字符。
我该怎么做才能解决此问题?有人可以帮我吗?

Both Log.i("lolo", line); and System.out.println("here is some chinese character 这是一些中文字") don't show characters correctly, i can not even see the chinese characters in the println() method. What can i do to fix this problem? Can anybody help me?

推荐答案

为了正确处理非ASCII字符,例如UTF-8多字节字符,它是了解这些字符的编码和显示方式很重要。

In order to correctly handle non-ASCII characters such as UTF-8 multi-byte characters, it's important to understand how these characters are encoded and displayed.

您的控制台(输出屏幕)可能不支持非ASCII字符的显示。在这种情况下,您的UTF-8字符将显示为垃圾内容。有时,您将能够在控制台上更改字符编码。有时不是。

Your console (output screen) may not support the display of non-ASCII characters. If that's the case, your UTF-8 characters will be displayed as garbage. Sometimes, you will be able to change the character encoding on the console. Sometimes not.

即使控制台正确显示了UTF-8字符,您的字符串也可能没有正确存储中文字符。您可能会认为这是正确的,因为您的编辑器会显示它们,但请确保您的编辑器的字符编码也支持UTF-8。

Even if the console correctly displayed UTF-8 characters, it's possible that your string does not correctly store the Chinese characters. You may think that it's correct because your editor displays them, but ensure that the character encoding of your editor also supports UTF-8.

这篇关于Android:如何读取包含汉字的txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆