使用UTF-8读取.txt文件

时间:2015-10-02 13:02:44

标签: android utf-8 inputstream

我有一个txt文件,其中包含UTF-8编码的单词。我把它放在"资产"文件夹,这是我读它们的方式:

private void readWordsFromFile() {
    AssetManager assetManager = context.getAssets();
    try {
        InputStream is = assetManager.open("words.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF8"));
        String line;
        while ((line = reader.readLine()) != null) {
            HashMap<String, String> tempMap = new HashMap<String, String>();
            tempMap.put("question", line);
            line = reader.readLine();
            tempMap.put("answer", line);
            words.add(tempMap); // adding to an ArrayList
        }
        reader.close();
    } catch (IOException e) {
        Toast toast = Toast.makeText(context, "Error during openin learning file", Toast.LENGTH_SHORT);
        toast.show();
    }
}

然后我把这些单词形成数组,然后将它们放在TextViews中。布局xml文件指定了UFT8编码:

<?xml version="1.0" encoding="utf-8"?>

但是仍然显示错误。我做错了什么?

1 个答案:

答案 0 :(得分:1)

解决方案:

我不得不更改txt文件编码:

资产文件夹 - &gt;我的文件 - &gt;右键单击 - &gt;属性 - &gt;将编码更改为UTF8