什么是getBytes(“UTF-8”),getBytes(“windows-1252”)和getBytes()之间的区别?

时间:2016-04-28 08:30:41

标签: 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();
        }

        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之间的区别。 但是当我看输出时,似乎没有区别。只有当我使用utf-16 cdompare windows-1252时才会有所不同。

输出:

> 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

任何人都可以解释为什么 utf-8和windows-1252看起来相同

干杯 亚历

2 个答案:

答案 0 :(得分:3)

这是因为您只在测试ASCII中使用了String字符(例如"Moage test String"},尝试使用"éèà"之类的特殊字符,您将会然后看到不同的结果。

答案 1 :(得分:0)

下面,

您使用的字符串字符属于ASCII范围。如果您的字符串包含任何特殊字符支持特殊字符的语言您的字节输出将被更改。

  

UTF-8通常是经过批准的标准,适用于任何地方。但是,Windows-任何编码都是特定于Windows的,并不保证可以在任何计算机上运行。

相关问题