繁体   English   中英

如何最好地将 byte[] 数组转换为字符串缓冲区

[英]How best to convert a byte[] array to a string buffer

我有许多需要转换为字符串缓冲区的 byte[] 数组变量。

有这种转换的方法吗?

谢谢

Thank you all for your responses..However I didn't make myself clear.... I'm using some byte[] arrays pre-defined as public static "under" the class declaration for my java program. 这些“字段”在流程的“生命周期”中被重用。 当程序发出状态消息时,(写入文件)我定义了一个字符串缓冲区(mesg_data),用于格式化状态消息。 因此,当程序执行时,我尝试了 msg2 = String(byte_array2) 我得到一个编译器错误:找不到符号符号:方法 String(byte[]) 位置:class APPC_LU62.java.LU62XnsCvr convrs_ID = String(conversation);

例子:

public class LU62XnsCvr extends Object
           .
           .
static String convrsID ; 
static byte[] conversation_ID = new byte[8] ;

所以我不能使用字符串变量的“动态”定义,因为同一个变量用于多次出现。

我希望我说清楚了 非常感谢

盖伊

String s = new String(myByteArray, "UTF-8");
StringBuilder sb = new StringBuilder(s);

有一个字节数组和编码的构造函数:

 byte[] bytes = new byte[200];
 //...

 String s = new String(bytes, "UTF-8");

为了将字节转换为字符,您需要指定编码:0-255 值(即:字节序列)的序列(通常长度为 1,2 或 3)映射到字符的方案。 UTF-8 可能是默认的最佳选择。

可以直接转成String

byte[] bytearray
....
String mystring = new String(bytearray)

然后转换为StringBuffer

StringBuffer buffer = new StringBuffer(mystring)

您可以使用

str = new String(bytes)

上面的代码所做的就是创建一个使用默认平台字符编码的 java 字符串(即 UTF-16)。

如果字节数组是从以平台默认字符编码编码的字符串创建的,这将很好地工作。

如果不是,您需要指定正确的字符编码(Charset)为

String str = new String (byte [] bytes, Charset charset)

它完全取决于字符编码,但你想要:

String value = new String(bytes, "US-ASCII");

这适用于 US-ASCII 值。

有关其他有效字符编码(例如 UTF-8),请参阅Charset

暂无
暂无

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

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