调试 ByteArrayOutputStream 字符串比较

debugging ByteArrayOutputStream string comparison

我对 Java 的 ByteArrayOutputStream 有一个奇怪的问题..

public static void main(String[] args) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    String expected = "{x={x=4, y=true}, y=true}";
    printToStream(ps);

    try {
        String content =  new String(baos.toByteArray());
        System.out.println(">content : "+content);
        System.out.println("-expected: "+expected);
        printBytes(content);
        printBytes(expected);
        if(content.equals(expected)==false) //HERE
            throw new RuntimeException( "program failed");
        baos.close();

    } catch ( UnsupportedEncodingException e) {
        throw new RuntimeException(" failed string extraction");
    } catch ( IOException e) {
        throw new RuntimeException(" cannote close the stream");
    } 
}

程序以 "program failed" 异常结束,因为字符串不相等,但在 Eclipse 控制台上它们看起来相同:

>content : {x={x=4, y=true}, y=true}
-expected: {x={x=4, y=true}, y=true}

此外,为了检查字符串的单个字节(因为如果我可以隔离单个字符,我可以发现字符串创建或编码有什么问题)我创建了一个方法来查看它们字节的十六进制值。但它们不是印刷!

public static void printBytes( String st){
    String bytes="";
    for(byte it: st.getBytes())
        st+=Integer.toHexString(it)+" ";
    System.out.println("HexValues: "+bytes);
}

我得到的不是 HexValues,而是一个空字符串

HexValues: 
HexValues: 

进一步调查 getBytes() 方法的文档

The behavior of this method when this string cannot be encoded in the default charset is unspecified

但是,如果我提供一个应该接受所有可能字符(UTF8 或 UTF16)作为 getBytes 参数的字符集,它仍然会失败(因为字符串是 UTF16 应该总是可以将其转换为 UTF8或理论上的 UTF16,唯一应该失败的转换是例如非 ASCII 字符的 ASCII)。

方法 printToStream( PrintStream ps) 是规范的一部分,所以我无法更改它。

真正的问题是:我需要理解为什么String的equals方法return false.

编辑: 在指向正确调试代码的答案后,我得到:

HexValues:  fffffffe  ffffffff  0  74  0  72  0  75  0  65  0  d  0  a 
HexValues:  fffffffe  ffffffff  0  74  0  72  0  75  0  65  0  a 

这是一辆失踪的马车return0x0d。 谢谢!

您的代码在

处有错误
 st+=Integer.toHexString(it)+" ";
 bytes+=Integer.toHexString(it)+" ";//use this instead

此错误导致函数输入修改:content 和 expected 被修改

在该方法中,您没有更改打印的字符串值。因此 bytes 的值为空。您正在更改参数字符串。

你应该使用

public static void printBytes( String st){
    String bytes="";
    for(byte it: st.getBytes())
        bytes+=Integer.toHexString(it)+" "; // not st
    System.out.println("HexValues: "+bytes);
}

对于平等情况。可能是您在字符串中有空格。尝试 trim 字符串并进行比较

if(content.trim().equals(expected.trim()) // no need to explicitly check if true or flase