我有一个文本文件,其中包含我需要预加载到 SQLite 数据库中的数据。我保存在 res/raw 中。
我使用 readTxtFromRaw()
读取整个文件,然后使用 StringTokenizer
类逐行处理文件。
但是 readTxtFromRaw
返回的 String
不显示文件中的外来字符。我需要这些,因为有些文字是西类牙语或法语。我错过了什么吗?
代码:
String fileCont = new String(readTxtFromRaw(R.raw.wordstext));
StringTokenizer myToken = new StringTokenizer(fileCont , "\t\n\r\f");
readTxtFromRaw 方法是:
private String readTxtFromRaw(Integer rawResource) throws IOException
{
InputStream inputStream = mCtx.getResources().openRawResource(rawResource);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
return byteArrayOutputStream.toString();
}
该文件是使用 Eclipse 创建的,所有字符在 Eclipse 中都显示正常。
这会不会与 Eclipse 本身有关?我设置了一个断点并在 Watch 窗口中检查了 myToken。我尝试手动将奇怪的字符替换为正确的字符(例如 í 或 é),但它不允许我这样做。
最佳答案
你检查过几种编码方式了吗?
- 源文件的编码是什么?
- 输出流的编码是什么?
byteArrayOutputStream.toString()
根据平台默认的字符编码进行转换。所以我猜它会去除外来字符或以不显示在输出中的方式转换它们。
您是否已尝试使用 byteArrayOutputStream.toString(String enc)
?尝试使用“UTF-8”或“iso-8859-1”或“UTF-16”作为编码。
关于android - 为什么使用 inputStream 不读取外来字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6238208/