Android OutputStreamWriter writes non-UTF-8 characters

1k views Asked by At

There's something weird happening to my code. I'm trying to open a file and append a generated string (which is based on time) to it, so that it can be used later on. In my app, this happens more then once, but somehow, this time it doesn't give me the result I'd like to see. To clarify:

I'm using the following code inside my class:

try {
    OutputStreamWriter oos = new OutputStreamWriter(context.openFileOutput(ARRANGED_TXT, Context.MODE_PRIVATE));

    oos.write(ArrangedTxtAsString);

    oos.close();
}
catch(FileNotFoundException e){
    Log.e("File Error", "File not found: " + e.toString());
}

and ARRANGED_TXT being defined as:

private static final String ARRANGED_TXT = "arranged_txt.txt";

ArrangedTxtAsString is a string, which looks like this:

Banana
Pineapple
Orange
Coconut
Strawberry

It was made using a StringBuilder.

Now, the problem is, is that the generated file looks like this:

enter image description here

It's not a problem with NotePad++, as other programs give the same result. One important thing to mention, is that although the text looks like it is made up out of non-UTF-8 characters, it is perfectly processed by the rest of the program. This may sound a bit weird, but what I'm trying to tell, is that the code is working fine, but the only problem there is, is that the text shown through a text-editor, doensn't correspond with what it should look like. You see, I'm quite a perfectionist and that's why I want it to get fixed. This might also be a problem in the future (debugging puposes etc.).

Edit:

It appears that it doesn't matter what the string contains: a single character, a number, or whatever; it gives the exact same result. Even writing "" results in those weird characters!

I really hope someone knows what's happening here! Thank you in advance.

1

There are 1 answers

1
FRL On

If you need to write UTF-8 MUST use the constructor with charset like:

OutputStreamWriter oos = new OutputStreamWriter(context.openFileOutput(ARRANGED_TXT, Context.MODE_PRIVATE),"UTF-8");

OutputStreamWriter(OutputStreamĀ out, StringĀ charsetName)

Otherwise the default encoding is used and not is utf-8 in all systems