Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read .txt assets as UTF-8 in Android through the assetManager?

Tags:

android

private void copyMB() {
    AssetManager assetManager = this.getResources().getAssets();
    String[] files = null;
    try {
        files = assetManager.list(assetDir);
    } catch (Exception e) {
        e.printStackTrace();
    }
    for(int i=0; i<files.length; i++) {
        InputStream in = null;
        FileOutputStream fos;
        try {
            in = assetManager.open(assetDir+"/" + files[i]);

            fos = openFileOutput(files[i], Context.MODE_PRIVATE);
            copyFile(in, fos);
            in.close();
            in = null;
            fos.flush();
            fos.close();
            fos = null;
        } catch(Exception e) {
            e.printStackTrace();
        }       
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {

    byte[] buffer = new byte[1024];
    int read;

    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}

My problem is that UTF-8 character such as åäö is replaced by wierd looking characters. How can I make sure that it my InputStream reader uses UTF-8? In normal Java it would be easy Writing … new InputStreamReader(filePath, "UTF-8"); But since I am getting it from the Asset folder I canot do that (I have to use the assetManager.open() method which wont take "UTF-8" as an argument.

Any ideas? :)

Thank you for your help.

like image 786
matphi Avatar asked Nov 29 '25 16:11

matphi


1 Answers

As you write yourself:

new InputStreamReader(in, "UTF-8");

creates a new stream reader with Utf-8 encoding. Just put it in the copyFile() method with your InputStream as the argument.

like image 198
Jave Avatar answered Dec 02 '25 05:12

Jave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!