[英]How to load a UTF-8 text file with InputStream
I want to load a .txt file from my assets folder into a text view by pressing a button. 我想通过按下按钮将资产文件夹中的.txt文件加载到文本视图中。 I did this so but my problem is that my text file is UTF-8 Encoded text and some strange characters are copied into my TextView instead my true words... Here is my code and method I wrote but I don't know where I should put "UTF-8" as an argument..
我是这样做的,但是我的问题是我的文本文件是UTF-8编码文本,并且一些奇怪的字符被复制到我的TextView中,而不是我的真实单词。这是我编写的代码和方法,但是我不知道我在哪里应该将“ UTF-8”作为参数。
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
try {
InputStream iFile = getAssets().open("mytext.txt");
String strFile = inputStreamToString(iFile);
Intent intent=new Intent(MyActivity.this,SecondActivity.class);
intent.putExtra("myExtra", strFile);
final int result=1;
startActivityForResult(intent, result);
} catch (IOException e) {
e.printStackTrace();
}
public String inputStreamToString(InputStream is) throws IOException {
StringBuffer sBuffer = new StringBuffer();
DataInputStream dataIO = new DataInputStream(is);
String strLine = null;
while ((strLine = dataIO.readLine()) != null) {
sBuffer.append(strLine + "\n");
}
dataIO.close();
is.close();
return sBuffer.toString();
}
Thanks for your help ;-) 谢谢你的帮助 ;-)
Following code reads your file into byte array buffer and converts it to string 以下代码将文件读入字节数组缓冲区,并将其转换为字符串
public String inputStreamToString(InputStream is) throws IOException {
byte[] buffer = new byte[is.available()];
int bytesRead = is.read(buffer);
return new String(buffer, 0, bytesRead, "UTF-8");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.