Reputation: 75
I want to load a .txt file from my assets folder into a text view by pressing a button. 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..
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 ;-)
Upvotes: 1
Views: 1859
Reputation: 28516
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");
}
Upvotes: 2