Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the use of ByteArrayOutputStream streams in the basics of Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

It is believed that many inexperienced people have no idea about how to use the ByteArrayOutputStream stream in the basic knowledge of Java. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

The use of Java ByteArrayOutputStream flow I. ByteArrayOutputStream flow definition

API description: this class implements a byte output stream in which the data is written to the byte array, and the buffer automatically grows when the data is written. It is invalid to close the stream, and there will be no exception when calling the method after closing the stream.

Second, ByteArrayOutputStream stream instance field / * buffer for storing data * / protected byte buf []; / * effective bytes in the buffer * / protected int count; 3, ByteArrayOutputStream stream constructor / * create a new byte array output stream. The default buffer size is 32 bytes * / public ByteArrayOutputStream () {this (32). } / * create a new byte array output stream with the specified size * / public ByteArrayOutputStream (int size) {if (size)

< 0) { throw new IllegalArgumentException("Negative initial size: " + size); } buf = new byte[size]; }四、ByteArrayOutputStream流方法 1)write(int b):写入指定的字节到此字节输出流中 /** * 写入指定的字节到此字节输出流中 */ public synchronized void write(int b) { ensureCapacity(count + 1); buf[count] = (byte) b; count += 1; } 2)write(byte b[], int off, int len):从指定数组的下标off开始写入len个字节到该输出流中 /** * 从指定数组的下标off开始写入len个字节到该输出流中 */ public synchronized void write(byte b[], int off, int len) { if ((off < 0) || (off >

B.length) | | (len

< 0) || ((off + len) - b.length >

0) {throw new IndexOutOfBoundsException ();} ensureCapacity (count + len); System.arraycopy (b, off, buf, count, len); count + = len;}

3) writeTo (OutputStream out): writes the contents of this byte output stream to the specified output stream

Write the contents of this byte output stream to the specified output stream * / public synchronized void writeTo (OutputStream out) throws IOException {out.write (buf, 0, count);}

4) reset (): resets this byte output stream to discard previously stored data

/ * reset this byte output stream to discard previously stored data * / public synchronized void reset () {count = 0;}

5) retrieve the data of the output stream

/ * convert this output stream to a byte array output * / public synchronized byte toByteArray () [] {return Arrays.copyOf (buf, count);} / * convert this output stream to a string output * / public synchronized String toString () {return new String (buf, 0, count) } / * convert the buffer contents to a string * / public synchronized String toString (String charsetName) throws UnsupportedEncodingException {return new String (buf, 0, count, charsetName) by specifying the encoding format;}

6) close (): it is invalid to close the stream. There will be no exception when calling other methods after closing.

/ * it is invalid to close the stream. Calling other methods after closing will not cause any exception * / public void close () throws IOException {} 5. The function of ByteArrayOutputStream stream

It has not been used for the time being, so it is not clear where to use it in the project, so you can understand its function for the time being.

ByteArrayOutputStream understanding

The first time I saw ByteArrayOutputStream was part of the source code of Nutch. Later, I frequently found traces of these two classes when it came to IO operations. I thought it was really easy to use, so summarize their usage.

The usage of ByteArrayOutputStream

The following is the record in JDK:

Public class ByteArrayOutputStream extends OutputStream

This class implements an output stream where the data is written to an byte array. The buffer automatically grows as the data is written. You can use toByteArray () and toString () to get the data.

It is not valid to close ByteArrayOutputStream. Methods in this class can still be called after closing the stream without generating any IOException.

My personal understanding is that ByteArrayOutputStream is used to cache data (the target of data writing (the original meaning of output stream), writing data to its internal buffer, which automatically grows, from which data can be extracted when the write is complete. For this reason, ByteArrayOutputStream is often used to store data for a single write.

Example:

Read binary data from a file and store it all in ByteArrayOutputStream.

FileInputStream fis=new FileInputStream ("test"); BufferedInputStream bis=new BufferedInputStream (fis); ByteArrayOutputStream baos=new ByteArrayOutputStream (); int c=bis.read (); / / read the next byte while in the bis stream {baos.write (c); c=bis.read ();} bis.close (); byte retArr [] = baos.toByteArray (); usage of ByteArrayInputStream

Relatively speaking, ByteArrayInputStream is relatively rare. First, take a look at the introduction in the JDK documentation:

Public class ByteArrayInputStreamextends InputStreamByteArrayInputStream

Contains an internal buffer that contains bytes read from the stream. The internal counter tracks the next byte to be supplied by the read method.

It is not valid to close ByteArrayInputStream. Methods in this class can still be called after closing the stream without generating any IOException.

Constructor:

ByteArrayInputStream (byte [] buf)

Note that it needs to provide an array of byte as a buffer.

Similar to the semantics of most Inputstream, you can read data from its buffer, so we can wrap another layer of inputstream around it to use the read method we need.

Personally, I think a better use is to read packets in the network. Since packets are generally of fixed length, we can first assign a large enough byte array, such as byte buf [] = new byte [1024].

Then call a method to get the packet in the network, for example:

Socket slots. Bais DataInputStream dis=new DataInputStream (s.getInputStream ()); dis.read (buf); / / store all data in buf (buf); / / treat the previous part as an input stream DataInputStream dis_2=new DataInputStream (bais); / / now you can use various read methods of dis_2 to read specified bytes

For example, the first byte is the version number, dis_2.readByte ()

Wait a minute...

The two wrappers in the above example seem a bit superfluous, but the advantage of using ByteArrayInputStream is that its data still exists after the stream is turned off.

After reading the above, have you mastered how to use ByteArrayOutputStream streams in the basics of Java? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report