package com.inmind.outputstream01; import java.util.Arrays; /* 5.字节数组和字符串的相互转换 字节数组--->字符串:构造方法 String(byte[] bytes) 通过使用平台的默认字符集解码指定的字节数组来构造新的 String 。 String(byte[] bytes, int offset, int length) 通过使用平台的默认字符集解码指定的字节子阵列来构造新的 String 字符串--->字节数组:成员方法 byte[] getBytes() 使用平台的默认字符集将该 String编码为一系列字节,将结果存储到新的字节数组中。 注意: 1.UTF-8:字母和数字都只占1个字节,而一个中文占3个字节 2.GBK:字母和数字都只占1个字节,而一个中文占2个字节 */ public class Demo03 { public static void main(String[] args) { String str = "abc"; //String->byte[] byte[] bytes = str.getBytes(); System.out.println(Arrays.toString(bytes));// 97 98 99 //byte[]-->String String s = new String(bytes); System.out.println(s); //中文转字节 String str1 = "中国"; byte[] bytes1 = str1.getBytes(); System.out.println(Arrays.toString(bytes1)); //字节转中文,帮我定义一个“国”字的字节数组,转为中文 byte[] bytes2 = {-27,-101,-67}; String str2 = new String(bytes2); System.out.println(str2); } }