Convert String to ByteArray with different encode using kotlin and java but got error result

hi, guys, I have a strange problem. let’s see the code:
I have a java class Test:

public class Test {
    public static void test() {
        System.out.println("GBK:   " + Arrays.toString("你好".getBytes(Charset.forName("GBK"))));
        System.out.println("UTF-8: " + Arrays.toString("你好".getBytes(StandardCharsets.UTF_8)));
    }
}

and kotlin main function:


fun main(vararg args: String) {
    println("GBK:   " + "你好".toByteArray(Charset.forName("GBK")).contentToString())
    println("UTF-8: " + "你好".toByteArray(StandardCharsets.UTF_8).contentToString())
    println("---------------↓Java↓-------------------")
    Test.test()
}

But I got the result:

GBK:   [-60, -29, -70, -61]
UTF-8: [-28, -67, -96, -27, -91, -67]
---------------↓Java↓-------------------
GBK:   [-28, -67, -96, -27, -91, -67]
UTF-8: [-26, -75, -93, -25, -118, -78, -29, -126, -67]

Why the Kotlin code with UTF-8 encode would equal the java code with GBK encode result?

Your code on my PC

GBK:   [-60, -29, -70, -61]
UTF-8: [-28, -67, -96, -27, -91, -67]
---------------↓Java↓-------------------
GBK:   [-60, -29, -70, -61]
UTF-8: [-28, -67, -96, -27, -91, -67]

Kotlin 1.3.50
openjdk version “11.0.4” 2019-07-16

Seems like a source encoding issue. My guess is that you have written both source files in UTF-8 but compiled the Java program using a different encoding.

Thanks for your reply.

As you said, I have written both source files in UTF-8 .

And I used IDEA to run the code.

"C:\Program Files\Java\jdk1.8.0_121\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar=63084:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_121\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_121\jre\lib\ext\access-bridge-64.jar;...

I noted that -Dfile.encoding=UTF-8 parameter.

why the error still occur? I am very confused… How can I fix this issue?

BTW, the env:

IntelliJ IDEA 2019.2.2 (Ultimate Edition)
Build #IU-192.6603.28, built on September 6, 2019

Runtime version: 11.0.3+12-b304.56 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 978M
Cores: 4


Java env:

java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)