Java getBytes(“UTF-8”)、getBytes(“windows-1252”)和getBytes()之间有什么区别?
我有下面的代码,它会产生令人困惑的输出Java getBytes(“UTF-8”)、getBytes(“windows-1252”)和getBytes()之间有什么区别?,java,encoding,utf-8,character-encoding,bytestream,Java,Encoding,Utf 8,Character Encoding,Bytestream,我有下面的代码,它会产生令人困惑的输出 import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; public class Main { String testString = "Moage test String"; public static void main(String[] args) { new Main();
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
public class Main {
String testString = "Moage test String";
public static void main(String[] args) {
new Main();
}
public Main(){
System.out.println("Default charset: "+Charset.defaultCharset());
System.out.println("Teststring: "+testString);
System.out.println();
System.out.println("get the byteStreeam of the test String...");
System.out.println();
System.out.println("Bytestream with default encoding: ");
for(int i = 0; i < testString.getBytes().length; i++){
System.out.print(testString.getBytes()[i]);
}
System.out.println();
System.out.println();
System.out.println("Bytestream with encoding UTF-8: ");
try {
for(int i = 0; i < testString.getBytes("UTF-8").length; i++){
System.out.print(testString.getBytes("UTF-8")[i]);
}
System.out.println();
System.out.println();
System.out.println("Bytestream with encoding windows-1252 (default): ");
for(int i = 0; i < testString.getBytes("windows-1252").length; i++){
System.out.print(testString.getBytes("windows-1252")[i]);
}
System.out.println();
System.out.println();
System.out.println("Bytestream with encoding UTF-16: ");
for(int i = 0; i < testString.getBytes("UTF-16").length; i++){
System.out.print(testString.getBytes("UTF-16")[i]);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
有人能解释一下为什么utf-8和windows-1252看起来一样吗
干杯
Alex这是因为您在测试
字符串中只使用ASCII
字符,这在您的案例中是“Moage测试字符串”
,请尝试使用特殊字符,例如“èèa”
,然后您将看到不同的结果。这是因为您在测试字符串中只使用ASCII
字符,在您的情况下“Moage test String”
,尝试使用特殊字符,例如“èè”
,您将看到不同的结果。这里
您使用了属于ASCII
范围的字符串。如果字符串包含任何支持特殊字符的特殊字符或语言,则字节输出将被更改
UTF-8是普遍认可的标准,适用于任何地方。但是,Windows任何编码都是Windows特定的,不能保证在任何机器上工作
这里,
您使用了属于ASCII
范围的字符串。如果字符串包含任何支持特殊字符的特殊字符或语言,则字节输出将被更改
UTF-8是普遍认可的标准,适用于任何地方。但是,Windows任何编码都是Windows特定的,不能保证在任何机器上工作
在测试字符串中放入一些特殊字符。您当前的测试数据不包括字符集之间的差异。谢谢!!我从未想过这会改变一些事情现在有一些不同。在测试字符串中放入一些特殊字符。您当前的测试数据不包括字符集之间的差异。谢谢!!我从未想过这会改变一些事情现在有一些不同。
> Default charset: windows-1252 Teststring: Moage test String
>
> get the byteStreeam of the test String...
>
> Bytestream with default encoding:
> 7711197103101321161011151163283116114105110103
>
> Bytestream with encoding UTF-8:
> 7711197103101321161011151163283116114105110103
>
> Bytestream with encoding windows-1252 (default):
> 7711197103101321161011151163283116114105110103
>
> Bytestream with encoding UTF-16:
> -2-1077011109701030101032011601010115011603208301160114010501100103