简体   繁体   中英

java encoding issue while writing file

I am creating a very simple application which reads some input from one file and generates another file with that information. I ran it on Windows 7 and it worked with no problems, but when I run it on Mac OS, special characters are not shown properly.

Here is my code:

Writer writer = new BufferedWriter(
    new OutputStreamWriter(
        new FileOutputStream(destiny),"utf-8"));
writer.write(infoFromInputFile);
writer.close();

I am declaring my FileOutputStream with UTF-8 codification, and when I checked the created file properties, it says that it is in UTF-8, but the special characters like ¿, á, é, í, ¡, etc. are displayed wrong.

Any ideas of why is this happening?

How did you check the output file? Perhaps the editor you opened it with, or the command you dumped it to the console with (or the console itself), incorrectly rendered the content of the file? (That is, perhaps the file is correct, and the thing you checked it with assumed it wasn't UTF-8.)

Alternatively, are you sure you opened the input file (presumably using a Reader ?) with the correct encoding?

You need to check a number of things:

  • First, I'd recommend calling flush() on the Writer, before you close it.

  • What was the actual encoding of the original file (the input file)? Were the input file(s) in two different encodings (one on Windows, a different one on Mac)? Or the same (maybe UTF-8 on both)? I'm guess the default encoding (the one that Java assumes, if you don't tell the Reader) might be different on Windows and Mac (or even between versions).

  • What encoding did you open the input file as, when you read it? (This should match what it was re the above).

  • Did you do anything between input and output, when processing the file, that might have introduced odd characters? (Like, for example, doing arithmetic on Unicode values.)

I found the solution. Mac uses a different codification for .java files than Windows and Linux (which I als tried and worked well). To create files with UTF-8 encoding, you must run your program with the following option:

java -Dfile.encoding=UTF-8 YourJavaClass

Thanks for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM