繁体   English   中英

Java打印unicode故障

[英]Java print unicode glitch

我目前正在编写一个程序来读取java类文件。 目前,我正在读取类文件的Constant-Pool( 在此处阅读)并将其打印到控制台。 但是当它被打印出来时,一些unicode似乎以这种方式弄乱我的终端,它看起来像这样(如果重要的话,我正在阅读的类文件是从Kotlin编译的,而终端I我使用的是IntelliJ IDEA终端,虽然在使用常规Ubuntu终端时似乎没有出现问题。): 在IntelliJ IDEA上搞砸了终端 我注意到的是一个奇怪的Unicode序列,我认为它可能是某种逃逸序列。

这是没有奇怪的unicode序列的整个输出:

{1=UTF8: (42)'deerangle/decompiler/main/DecompilerMainKt', 2=Class index: 1, 3=UTF8: (16)'java/lang/Object', 4=Class index: 3, 5=UTF8: (4)'main', 6=UTF8: (22)'([Ljava/lang/String;)V', 7=UTF8: (35)'Lorg/jetbrains/annotations/NotNull;', 8=UTF8: (4)'args', 9=String index: 8, 10=UTF8: (30)'kotlin/jvm/internal/Intrinsics', 11=Class index: 10, 12=UTF8: (23)'checkParameterIsNotNull', 13=UTF8: (39)'(Ljava/lang/Object;Ljava/lang/String;)V', 14=Method name index: 12; Type descriptor index: 13, 15=Bootstrap method attribute index: 11; NameType index: 14, 16=UTF8: (12)'java/io/File', 17=Class index: 16, 18=UTF8: (6)'<init>', 19=UTF8: (21)'(Ljava/lang/String;)V', 20=Method name index: 18; Type descriptor index: 19, 21=Bootstrap method attribute index: 17; NameType index: 20, 22=UTF8: (15)'getAbsolutePath', 23=UTF8: (20)'()Ljava/lang/String;', 24=Method name index: 22; Type descriptor index: 23, 25=Bootstrap method attribute index: 17; NameType index: 24, 26=UTF8: (16)'java/lang/System', 27=Class index: 26, 28=UTF8: (3)'out', 29=UTF8: (21)'Ljava/io/PrintStream;', 30=Method name index: 28; Type descriptor index: 29, 31=Bootstrap method attribute index: 27; NameType index: 30, 32=UTF8: (19)'java/io/PrintStream', 33=Class index: 32, 34=UTF8: (5)'print', 35=UTF8: (21)'(Ljava/lang/Object;)V', 36=Method name index: 34; Type descriptor index: 35, 37=Bootstrap method attribute index: 33; NameType index: 36, 38=UTF8: (19)'[Ljava/lang/String;', 39=Class index: 38, 40=UTF8: (17)'Lkotlin/Metadata;', 41=UTF8: (2)'mv', 42=Int: 1, 43=Int: 11, 44=UTF8: (2)'bv', 45=Int: 0, 46=Int: 2, 47=UTF8: (1)'k', 48=UTF8: (2)'d1', 49=UTF8: (58)'WEIRD_UNICODE_SEQUENCE', 50=UTF8: (2)'d2', 51=UTF8: (0)'', 52=UTF8: (10)'Decompiler', 53=UTF8: (17)'DecompilerMain.kt', 54=UTF8: (4)'Code', 55=UTF8: (18)'LocalVariableTable', 56=UTF8: (15)'LineNumberTable', 57=UTF8: (13)'StackMapTable', 58=UTF8: (36)'RuntimeInvisibleParameterAnnotations', 59=UTF8: (10)'SourceFile', 60=UTF8: (20)'SourceDebugExtension', 61=UTF8: (25)'RuntimeVisibleAnnotations'}
AccessFlags: {ACC_PUBLIC, ACC_FINAL, ACC_SUPER}

这是在Sublime Text中打开的Unicode序列: 崇高文本中的奇怪unicode

关于这一切的问题是:为什么这个Unicode打破了IntelliJ IDEA中的控制台,这在Kotlin-Class-Files中是常见的,在打印之前可以做些什么来从String中删除所有这些“转义序列”?

出于某种不可思议的原因,当Sun Microsystems设计Java时,他们决定使用非UTF8编码在常量池中编码字符串。 它是仅由java编译器和类加载器使用的自定义编码。

更糟糕的是,在JVM文档中他们决定称之为UTF8。 但它不是 UTF8,他们选择的名称会引起很多不必要的混淆。 所以,我在这里推测的是你看到他们称之为UTF8,所以你把它当作真正的 UTF8来对待,结果就是你收到了垃圾。

您需要在JVM规范中查找CONSTANT_Utf8_info的描述,并编写一个根据其规范对字符串进行解码的算法。

为方便起见,这里有一些我编写的代码:

public static char[] charsFromBytes( byte[] bytes )
{
    int t = 0;
    int end = bytes.length;
    for( int s = 0;  s < end;  )
    {
        int b1 = bytes[s] & 0xff;
        if( b1 >> 4 >= 0 && b1 >> 4 <= 7 ) /* 0x0xxx_xxxx */
            s++;
        else if( b1 >> 4 >= 12 && b1 >> 4 <= 13 ) /* 0x110x_xxxx 0x10xx_xxxx */
            s += 2;
        else if( b1 >> 4 == 14 ) /* 0x1110_xxxx 0x10xx_xxxx 0x10xx_xxxx */
            s += 3;
        t++;
    }
    char[] chars = new char[t];
    t = 0;
    for( int s = 0;  s < end;  )
    {
        int b1 = bytes[s++] & 0xff;
        if( b1 >> 4 >= 0 && b1 >> 4 <= 7 ) /* 0x0xxx_xxxx */
            chars[t++] = (char)b1;
        else if( b1 >> 4 >= 12 && b1 >> 4 <= 13 ) /* 0x110x_xxxx 0x10xx_xxxx */
        {
            assert s < end : new IncompleteUtf8Exception( s );
            int b2 = bytes[s++] & 0xff;
            assert (b2 & 0xc0) == 0x80 : new MalformedUtf8Exception( s - 1 );
            chars[t++] = (char)(((b1 & 0x1f) << 6) | (b2 & 0x3f));
        }
        else if( b1 >> 4 == 14 ) /* 0x1110_xxxx 0x10xx_xxxx 0x10xx_xxxx */
        {
            assert s < end : new IncompleteUtf8Exception( s );
            int b2 = bytes[s++] & 0xff;
            assert (b2 & 0xc0) == 0x80 : new MalformedUtf8Exception( s - 1 );
            assert s < end : new IncompleteUtf8Exception( s );
            int b3 = bytes[s++] & 0xff;
            assert (b3 & 0xc0) == 0x80 : new MalformedUtf8Exception( s - 1 );
            chars[t++] = (char)(((b1 & 0x0f) << 12) | ((b2 & 0x3f) << 6) | (b3 & 0x3f));
        }
        else
            assert false;
    }
    return chars;
}

迈克的答案已经涵盖了Java类文件并不完全使用UTF8编码这一事实,但我想我会提供更多有关它的信息。

Java类文件中使用的编码称为Modified UTF-8(或MUTF-8)。 它有两种不同于常规UTF-8的方式:

  • 使用双字节序列对空字节进行编码
  • BMP之外的代码点用代理对表示,如UTF16中所示。 该对中的每个代码点依次使用常规UTF8编码以三个字节编码。

第一个更改是编码数据不包含原始空字节,这使得在编写C代码时更容易处理。 第二个变化是由于早在90年代,UTF-16风靡一时,并且不清楚UTF-8最终会胜出。 事实上,Java出于类似的原因使用16位字符。 用代理对编码星体字符使得在16位世界中处理起来更容易。 请注意,大约在同一时间设计的Javascript与UTF-16字符串具有类似的问题。

无论如何,编码和解码MUTF-8非常简单。 这很烦人,因为它不是在任何地方构建的。 解码时,您以与UTF-8相同的方式进行解码,您必须更加宽容,除了技术上无效的序列UTF-8(尽管使用相同的编码),然后替换适用的代理对。 编码时,您可以执行相反的操作。

请注意,这仅适用于Java字节码。 Java中的程序员通常不必处理MUTF-8,因为Java在其他地方使用UTF-16和真正的UTF-8混合。

IntelliJ的控制台很可能将字符串的某些字符解释为控制字符(与Intellij产品中的Colorize控制台输出相比 )。

最有可能的是,它将是ANSI终端仿真,您可以通过执行轻松验证

System.out.println("Hello "
    + "\33[31mc\33[32mo\33[33ml\33[34mo\33[35mr\33[36me\33[37md"
    + " \33[30mtext");

如果您看到使用不同颜色打印的文本,则它是ANSI终端兼容的解释。

但是在从未知来源打印字符串时删除控制字符总是一个好主意。 类文件中的字符串常量不需要具有人类可读的内容。

一个简单的方法就是这样做

System.out.println(string.replaceAll("\\p{IsControl}", "."));

这将在打印前用点替换所有控制字符。

如果你想得到一些关于实际char值的诊断,你可以使用,例如

System.out.println(Pattern.compile("\\p{IsControl}").matcher(string)
    .replaceAll(mr -> String.format("{%02X}", (int)string.charAt(mr.start()))));

这需要Java 9,但当然,也可以为早期的Java版本实现相同的逻辑。 它只需要更冗长的代码。

Pattern.compile("\\\\p{IsControl}")返回的Pattern实例Pattern.compile("\\\\p{IsControl}")可以存储和重用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM