Write text file in UCS-2 Little Endian, Java
Asked Answered
P

2

3

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.

Peneus answered 13/6, 2013 at 7:54 Comment(0)
C
10

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.

Changteh answered 13/6, 2013 at 7:56 Comment(1)
Thank You very much, this did exactly what I wanted. :)Peneus
I
2

I came across this exact issue on Jython.

On Jython 2.5.2 Jon Skeet 's answer doesn't work. You need

write('\xff\xfe')

Hope this helps someone else.

Ist answered 14/8, 2013 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.