Java byte數(shù)組操縱方式代碼實例解析
字節(jié)數(shù)組的關(guān)鍵在于它為存儲在該部分內(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ù)組合并
/**
* 將所有的字節(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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python處理文本文件實現(xiàn)生成指定格式文件的方法
這篇文章主要介紹了python處理文本文件實現(xiàn)生成指定格式文件的方法,有一定的實用價值,需要的朋友可以參考下2014-07-07
Python中sorted()函數(shù)之排序的利器詳解
sorted()函數(shù)是Python中的內(nèi)置函數(shù),用于對可迭代對象進行排序,下面這篇文章主要給大家介紹了關(guān)于Python中sorted()函數(shù)之排序的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-08-08
Python bsddb模塊操作Berkeley DB數(shù)據(jù)庫介紹
這篇文章主要介紹了Python bsddb模塊操作Berkeley DB數(shù)據(jù)庫介紹,這里簡單介紹一些關(guān)于bsddb的使用方法,需要的朋友可以參考下2015-04-04

