字節(jié)數(shù)組的關鍵在于它為存儲在該部分內(nèi)存中的每個8位值提供索引(快速),精確的原始訪問,并且您可以對這些字節(jié)進行操作以控制每個位。 壞處是計算機只將每個條目視為一個獨立的8位數(shù) - 這可能是你的程序正在處理的,或者你可能更喜歡一些強大的數(shù)據(jù)類型,如跟蹤自己的長度和增長的字符串 根據(jù)需要,或者一個浮點數(shù),讓你存儲說3.14而不考慮按位表示。 作為數(shù)據(jù)類型,在長數(shù)組的開頭附近插入或移除數(shù)據(jù)是低效的,因為需要對所有后續(xù)元素進行混洗以填充或填充創(chuàng)建/需要的間隙。
java官方提供了一種操作字節(jié)數(shù)組的方法——內(nèi)存流(字節(jié)數(shù)組流)ByteArrayInputStream、ByteArrayOutputStream
ByteArrayOutputStream——byte數(shù)組合并
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * 將所有的字節(jié)數(shù)組全部寫入內(nèi)存中,之后將其轉化為字節(jié)數(shù)組 */ 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數(shù)組截取
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * 從內(nèi)存中讀取字節(jié)數(shù)組 */ 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)); } |
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/wangbin2188/p/11512192.html