简体   繁体   中英

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. 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 ;-)

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM