Write text file in UCS-2 Little Endian, Java

Tunerx picture Tunerx · Jun 13, 2013 · Viewed 9.4k times · Source

I'm trying to write .txt file and it have to be UCS-2 Little Endian, but when I tried

writer = new PrintWriter(path, "UTF-16LE");

From what I read it should be the same, but it won't work in specific application on server. When I open file which works (created manually) in Notepad++ it says that it's "UCS-2 Little Endian" but when it's created in Java like this it says "UCS-2 LE w/o BO" and server cannot read it.

How could I write it so it will work? This is whole code:

writer = new PrintWriter(path, "UTF-16LE");
for (int j = (i - itemsInPlaylist + 1); j <= i; j++) {
    writer.println(listParsedFile.get(j).getNameOfFile());
}
itemsInPlaylist = 0;
writer.close();

Thanks for any suggestions.

Answer

Jon Skeet picture Jon Skeet · Jun 13, 2013

It sounds like you need to write a byte-order mark first, so that your application can detect the encoding. (It's not clear what you mean by "it says" - clearly whatever "it" is can guess that it's UTF-16LE, but less reliably than when you've got the BOM.)

So just add:

writer.write("\uFEFF");

before you write anything else.