不带'ln'的字符串的System.out.print [英] System.out.print of string without 'ln'

查看:92
本文介绍了不带'ln'的字符串的System.out.print的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组,如下所示:

I have a byte array which looks like this:

[0, 0, 0, 0, 0, 0, 0, 0, 122, 98, 117, 54, 46, 0, 0, 115, 122, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 121, 116, 117, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 107, 111, 98, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 122, 42, 109, 111, 119, 40, 0, 0, 0, 0, 0, 0, 107, 111, 98, 0, 0, 0, 0, 0, 98, 111, 40]

我想将其打印为字符串,所以我写了以下代码:

I wanted to print it as a string, so I wrote the following code:

System.out.println(new String(byteArray));

,但没有输出。接下来,我尝试了以下代码:

but there is no output. Next, I tried the following code:

for(byte b: byteArray){
 System.out.print((char) b);
}

但同样没有输出。但是当我尝试以下代码时:

but again there is no output. But when I tried the following code:

for(byte b: byteArray){
 System.out.println((char) b);
}

我能够看到这些值。

我的问题是,为什么我不能创建字符串,或者为什么第一次从 byteArray 打印值失败?

My question is, why can't I create a string or why did the first printing of values from byteArray fail?

推荐答案

您的字节数组主要是不可打印的字符,并且混合了一些随机字母。
但是,您所需要的只是

Your byte array is mostly non printable characters, with a few random letters mixed in. But all you need is

String myString = new String(byteArray);

这将为您提供有效的字符串。

which will give you a valid string.

尝试以下代码,因为它可能会更好地说明您遇到的问题。

Try out the following code, as maybe it will better illustrate the issue your having.

 for (char c : new String(byteArray).toCharArray())
  {
     System.out.printf("Character: %s Hex: %02x \r",c,(int)c);
  }

这篇关于不带'ln'的字符串的System.out.print的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆