Search code examples
javacharacter-encodingrandomaccessfile

Write non english characters using a RandomAccessFile in java


I am trying to write some text to a file using a RandomAccessFile object but the non-english characters are not saved correctly.

Specifically, this sentence --> "und NotenstEnder Libero"

is saved like this --> "und Notenst•nder Libero"

where 'E' character is not english (the ascii code is 917 i think).

The code i am using is this:

file = new RandomAccessFile(path, "rw");
...
file.seek(file.length());
file.writeBytes("The data i want");

How can i avoid this and write the correct text?

(PS: I know about file.writeChars, and i am wondering if there is another way!)


Solution

  • The main problem might be your file encoding. You should use the correct encoding (probably UTF-8) , e.g.:

    byte[] b = "The data i want".getBytes("UTF-8");
    file.write(b);
    

    Note that if you're using a text viewer/editor to check the file, depending on which one you're using you might have to write a UTF-8 byte order mark at the beginning of the file or tell the viewer/editor to use UTF-8 if it can't figure it out by itself.