The key to a byte array is that it provides indexed (fast), precise raw access to each 8-bit value stored in that portion of memory, and you can manipulate those bytes Make operations to control each bit. The downside is that the computer just sees each entry as a separate 8-bit number - this might be what your program is dealing with, or you might prefer some more powerful data type like a string that keeps track of its own length and grows as needed , or a float that lets you store say 3.14 regardless of bitwise representation. As a data type, inserting or removing data near the beginning of a long array is inefficient because all subsequent elements need to be shuffled to fill or fill the created/required gaps.
java officially provides a method to operate byte arrays - memory stream (byte array stream) ByteArrayInputStream, ByteArrayOutputStream
ByteArrayOutputStream - byte array merger
/** * 将所有的字节数组全部写入内存中,之后将其转化为字节数组 */ 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 array interception
/** * 从内存中读取字节数组 */ 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)); }
Related learning recommendations: Java video tutorial
The above is the detailed content of Example analysis of Java byte array manipulation code. For more information, please follow other related articles on the PHP Chinese website!