Error writing file on Android

1

I'm trying to create a file on Android, but a letter is appearing 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 bytes. A byte pops up I do not know 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?

    
asked by anonymous 13.07.2015 / 01:34

1 answer

3

The " problem " is in the decimal representation by the chosen table, it is known as DBCS a> typically assigned to UTF-8 and UTF-16;

chars[7] = (char)153;

The decimal-153 is part of the extended ASCII table (128-255) in which case representation symbol will differ according to the Charset table defined 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. br>
ISO 8859-1

  

™   

UTF-8

  

Ù


So one of the solutions would be:

Writer w = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("ISO-8859-1"));
    
13.07.2015 / 04:55