0

I've this code

 //write a file in a specific directory
public static void writeFile(String comment, String outputFileName) {
    FileWriter fWriter = null;
    BufferedWriter writer = null; 
    try {
        fWriter = new FileWriter(outputFileName,true);
        writer = new BufferedWriter(fWriter);
        writer.write(comment);
        writer.newLine();
        writer.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

But when I save the file in outputFileName, it lost every special character.

File output format is .txt

Some solution?

Thanks a lot

Fabio
  • 159
  • 1
  • 4
  • 13
  • 1
    Already answered... http://stackoverflow.com/questions/6998905/java-bufferedwriter-object-with-utf-8 – Tommaso Bertoni Mar 02 '15 at 10:52
  • There is no such thing as a "file output format". `txt` is just an extension. You could call a text file "foo.exe" for all the OS cares. What matters here is that you use a `Writer` which converts the characters you give it into bytes, and the bytes which are output depend on the encoding use. And since you don't specify any, well, the default platform encoding is used... – fge Mar 02 '15 at 11:01

1 Answers1

2

FileWriter uses the platform-default encoding. It's very rarely a good idea to use that class, IMO.

I would suggest you use an OutputStreamWriter specifying the encoding you want - where UTF-8 is almost always a good choice, when you have a choice.

If you're using Java 7 or higher, Files.newBufferedWriter is your friend - and with Java 8, there's an overload without a Charset parameter, in which case UTF-8 is used automatically.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Another solution to ensure that the characters are indeed writable is to use an `OutputStreamWriter`, since a version of it accepts a `CharsetEncoder` as an argument which you can use to `.onUnmappableCharacter(CodingErrorAction.REPORT)` (conversely, there is a version of `InputStreamReader` accepting a `CharsetDecoder` as an argument) – fge Mar 02 '15 at 11:03