使用 UTF-8 读取 .txt 文件
Reading .txt file with UTF-8
我有一个 txt 文件,其中包含采用 UTF-8 编码的单词。我把它放在 "assets" 文件夹中,这是我阅读它们的方式:
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"?>
但是还是显示错误。我做错了什么?
解决方案:
我必须更改 txt 文件编码:
assets文件夹->我的文件->右键->属性->将编码更改为UTF8
我有一个 txt 文件,其中包含采用 UTF-8 编码的单词。我把它放在 "assets" 文件夹中,这是我阅读它们的方式:
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"?>
但是还是显示错误。我做错了什么?
解决方案:
我必须更改 txt 文件编码:
assets文件夹->我的文件->右键->属性->将编码更改为UTF8