4

I wrote a android app in java to get user answers and save them in a file. The problem is that this file is saved in utf-8. The end user will open these files in the IBM SPSS, an application for windows that can read files only in ANSI (windows-1252).

How do I create files in ANSI code to save in a SD card from java-android app?

I think I know that to convert Strings to ANSI I should use:

String unicode = new String(asciiBytes, "windows-1252");

Is that correct?

My code to save the file is this:

File interviewFile = new File(placeOfSDD, fileName);
FileWriter writer = new FileWriter(interviewFile, true);
writer.append(textBody);
writer.flush();
writer.close();

"textBody" is the String to convert to ANSI, and the "interviewFile" is the file to be saved as ANSI too.

Thanks for the help!!

NaN
  • 8,596
  • 20
  • 79
  • 153

1 Answers1

11

Strings are represented within the JVM as Unicode. When you write it out, you need to convert it to an appropriate character set.

To do this, use an OutputStreamWriter and specify the Charset.

OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file, true), 
                                                   "windows-1252");
writer.append(textBody);
writer.close();

Regarding your first question:

I think I know that to convert Strings to ANSI I should use:
String unicode = new String(asciiBytes, "windows-1252");
Is that correct?

Given an array of bytes representing characters in the 'windows-1252' character set, this code will construct you the appropriate Java String (internally represented as Unicode within the JVM). This isn't "converting Strings to ANSI" ... it's doing the opposite: converting 'windows-1252' to Unicode.

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
  • Is there an easy way to specify what to do with the characters that cannot be represented in CP1252? – sarnold Jun 27 '12 at 02:20
  • @sarnold: If you want more control of the encoding process, you're meant to use a [CharsetEncoder](http://docs.oracle.com/javase/6/docs/api/java/nio/charset/CharsetEncoder.html), but I never have. – Greg Kopff Jun 27 '12 at 02:23
  • Very short answer, but sharp! Thanks!! That solved the case! I use that because my OS is in Portuguese (Brazil) language. – NaN Jun 27 '12 at 02:55