JavaでByte []配列を文字列に変換する方法
場合によっては、String変数をバイト配列形式(JCE暗号化など)に変換する必要があります。 しかし、その後どうやってconvert a Byte[] array to Stringするのでしょうか?
次のコードのような単純なtoString()関数は機能していません。 元のテキストではなく、バイト値が表示されます。
String s = bytes.toString();
Byte配列をString形式に正しく変換するには、Stringオブジェクトを明示的に作成し、それにByte配列を割り当てる必要があります。
String s = new String(bytes);
public class TestByte
{
public static void main(String[] argv) {
String example = "This is an example";
byte[] bytes = example.getBytes();
System.out.println("Text : " + example);
System.out.println("Text [Byte Format] : " + bytes);
System.out.println("Text [Byte Format] : " + bytes.toString());
String s = new String(bytes);
System.out.println("Text Decryted : " + s);
}
}
出力
Text : This is an example Text [Byte Format] : [B@187aeca Text [Byte Format] : [B@187aeca Text Decryted : This is an example