在java中从字节数组转换为字符串,字符串转换为字节数组 [英] Convert from byte array to string and string to byte array in java

查看:231
本文介绍了在java中从字节数组转换为字符串,字符串转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

将byte []转换为String然后再转换为byte []

我有以下代码,我正试图通过测试,但似乎无法理解我的想法java世界中各种形式的编码。

I have the following piece of code, I'm trying to get the test to pass, but can't seem to get my head around the various forms of encoding that go on in the java world.

import java.util.Arrays;

class Test {

static final byte[] A = { (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66, (byte)0x77, (byte)0x88, (byte)0x99, (byte)0x00, (byte)0xAA };

public static void main(String[] args) {

    String s = new String(A);

    byte[] b = s.getBytes();

    if (Arrays.equals(A,b)) { 
       System.out.println("TEST PASSED!"); 
    }
    else {
       System.out.println("TEST FAILED!");
    }

}
}

我猜我的问题是:将一个字节数组的任意字节转换为Java字符串的正确方法是什么,然后将相同的Java字符串转换为另一个字节数组,它将具有与原始字节数组相同的长度和相同的内容?

I guess my question is: What is the correct way to convert a byte array of arbitary bytes to a Java String, then later on convert that same Java String to another byte array, which will have the same length and same contents as the original byte array?

推荐答案

尝试特定的编码:

String s = new String(A, "ISO-8859-1");

byte[] b = s.getBytes("ISO-8859-1");

ideone link

这篇关于在java中从字节数组转换为字符串,字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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