java官方提供了一種操作字節數組的方法——內存流(字節數組流)ByteArrayInputStream、ByteArrayOutputStream
ByteArrayOutputStream——byte數組合並
/** * 將所有的字節數組全部寫入內存中,之后將其轉化為字節數組 */ public static void main(String[] args) throws IOException { String str1 = "132"; String str2 = "asd"; ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write(str1.getBytes()); os.write(str2.getBytes()); byte[] byteArray = os.toByteArray(); System.out.println(new String(byteArray)); }
ByteArrayInputStream——byte數組截取
/** * 從內存中讀取字節數組 */ public static void main(String[] args) throws IOException { String str1 = "132asd"; byte[] b = new byte[3]; ByteArrayInputStream in = new ByteArrayInputStream(str1.getBytes()); in.read(b); System.out.println(new String(b)); in.read(b); System.out.println(new String(b)); }