Java byte數(shù)組操縱方式代碼實例解析
字節(jié)數(shù)組的關(guān)鍵在于它為存儲在該部分內(nèi)存中的每個8位值提供索引(快速),精確的原始訪問,并且您可以對這些字節(jié)進(jìn)行操作以控制每個位。 壞處是計算機只將每個條目視為一個獨立的8位數(shù) - 這可能是你的程序正在處理的,或者你可能更喜歡一些強大的數(shù)據(jù)類型,如跟蹤自己的長度和增長的字符串 根據(jù)需要,或者一個浮點數(shù),讓你存儲說3.14而不考慮按位表示。 作為數(shù)據(jù)類型,在長數(shù)組的開頭附近插入或移除數(shù)據(jù)是低效的,因為需要對所有后續(xù)元素進(jìn)行混洗以填充或填充創(chuàng)建/需要的間隙。
java官方提供了一種操作字節(jié)數(shù)組的方法——內(nèi)存流(字節(jié)數(shù)組流)ByteArrayInputStream、ByteArrayOutputStream
ByteArrayOutputStream——byte數(shù)組合并
/** * 將所有的字節(jié)數(shù)組全部寫入內(nèi)存中,之后將其轉(zhuǎn)化為字節(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ù)組截取
/** * 從內(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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
