Character encoding in java

I tried the code below:

public static void main(String[] args) throws IOException {
    String s = "NETWORK";
    try (
            FileOutputStream fos = new FileOutputStream("d:/endian.txt");
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF_16BE");) {
        osw.write(s);
        osw.flush();

    }
}

after starting, I get a file that contains the following chain: NETWORK; the size of the received file is 14 bytes (7 characters * 2 bytes). note the spaces between the characters of the chain. when I change the encoding with: UTF_16LE, I get a file size of 14 bytes, which contains the following line: NETWORK. no spaces between characters !!. I expect the line as follows: NETWOR K. I used notepad to open the file. Can anyone explain this behavior?

+4
source share
2 answers

Binary representation of the string "NETWORK" using:

  • UTF_16BE :

    00 4E 00 45 00 54 00 57 00 4F 00 52 00 4B (: N E T W O R K)

  • UTF_16LE:

    4E 00 45 00 54 00 57 00 4F 00 52 00 4B 00 (: NETWORK)

, , , Notepad UTF_16BE "NETWORK" ANSI UTF_16LE "NETWORK" UNICODE.

, hex editor, , , .

+4

. . , , . NotePad ++ .

+1

All Articles