java - 调试 ByteArrayOutputStream 字符串比较

标签 java encoding

我对 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");
    } 
}

程序以“程序失败”异常结束,因为字符串不相等,但在 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 参数的字符集,它仍然会失败(因为 String 是 UTF16 应该总是可以将其转换为理论上,UTF8 或 UTF16 唯一会失败的转换是例如非 ASCII 字符的 ASCII 转换)。

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

真正的问题是:我需要理解为什么 String 的 equals 方法返回 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 

缺少回车符0x0d。 谢谢!

最佳答案

您的代码
中有错误

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

此错误导致函数输入修改:内容和预期被修改

关于java - 调试 ByteArrayOutputStream 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30422570/

相关文章:

Java while循环打印平方数不能使用int?

java - Spring Boot Jackson 日期和时间戳格式

oracle - PL/SQL Developer 找不到带有俄文字母的记录

asp.net - 非 ASCII 字符需要 web.config 吗?

java - 在 libgdx 上捕获 onClose 窗口事件

java - 如何让 java swing 组合框显示数组中的列而不是它正在显示的内容?

java - 更新子文档的所有元素,其中子文档是列表的一部分

google-chrome - chrome 如何建立正确的字符编码?

java - 授权 header 的 Grails Base64 解码在解码时格式错误

java - 如何处理电子邮件主题中的 x-mac-ce 编码