开发者

Convert from byte array to string and string to byte array in java [duplicate]

开发者 https://www.devze.com 2023-04-06 19:02 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Conversion of byte[] into a String and then back to a byte[]
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Conversion of byte[] into a String and then back to a byte[]

I have the following piece of code, I'm trying to get the test to pass, but c开发者_高级运维an'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!");
    }

}
}

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?


Try a specific encoding:

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

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

ideone link


Use Base64.

Apache Commons Codec has a Base64 class which supports the following interface:

String str = Base64.encodeBase64String(bytes);
byte[] newBytes = Base64.decodeBase64(str);
0

精彩评论

暂无评论...
验证码 换一张
取 消