Error writing file on Android

Asked

Viewed 94 times

1

I’m trying to create a file on Android, but is appearing a letter that I do not want to be written. Note the code:

File file = new File(Environment.getExternalStorageDirectory().toString(), "Arquivo.sth");
try { file.createNewFile(); }
catch (Exception e) { file = null; }
if (file != null) {
    try {
        char[] chars = new char[8];
        chars[0] = (char)84;
        chars[1] = (char)66;
        chars[2] = (char)76;
        chars[3] = (char)33;
        chars[4] = (char)107;
        chars[5] = (char)0;
        chars[6] = (char)5;
        chars[7] = (char)153;

        Writer w = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8"));
        w.write(chars, 0, chars.length);
        w.close();
    } catch (Exception e) {

    }
}

The code can write all the characters. However, the file should have 8 bytes, but it has 9. A byte appears from where and it appears in the file before the last character.

Is it because I’m using UTF-8? Which charset should I use in this case?

1 answer

3


The "problem" is in the decimal representation by the chosen table, it is known as DBCS normally allocated to UTF-8 and UTF-16;

chars[7] = (char)153;

The decimal-153 is part of the extended table ASCII (128-255) in this case the representation symbol will differ according to the Charset table set for representation:

Using ISO 8859-1 (aka ISO Latin-1), an 8-byte file will be generated, in UTF-8 many of these representations use 2 bytes, which is the case of decimal 153 in UTF-8.

ISO 8859-1


UTF-8

Ù



Therefore, one of the solutions would be:

Writer w = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("ISO-8859-1"));
  • It worked! Thank you. Now bytes are being written correctly, but when I open the Windows notepad the characters appear in Japanese or Chinese, you can fix this?

  • @Jhonasboeno has yes, I will better consolidate my answer explaining the best practice that is using UNICODE, I just need some free time for it, tonight I do.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.