Java IO Learning--(v) byte and character array

Source: Internet
Author: User

Table of Contents

    • Read the array from InputStream or reader
    • Write an array from OutputStream or writer

A common byte and character array in Java stores data temporarily in the app. These arrays are also the usual source of data read or written to the destination. You can also load a file into an array if you need to read a lot of the contents of the file while the program is running. Of course you can read these arrays by specifying the index directly. But what components do you use if the design becomes a inputstream or reader instead of reading some data from an array?

from InputStream or Reader the array is read in

Reads data from an array with bytearrayinputstream or CharArrayReader encapsulated bytes or character arrays. In this way, the bytes and characters can be read as an array.

Examples are as follows:

01 byte[] bytes = newbyte[1024];
02
03  
04
05 //把数据写入字节数组...
06
07  
08
09 InputStream input = newByteArrayInputStream(bytes);
10
11  
12
13 //读取第一个字节
14
15 intdata = input.read();
16
17 while(data != -1) {
18
19 //操作数据
20
21  
22
23 //读下一个字节
24
25 data = input.read();
26
27 }

It can also be used to read a character array in the same way, as long as the character array is encapsulated on the CharArrayReader.

through OutputStream or Writer Write Array

Similarly, data can be written to Bytearrayoutputstream or Chararraywriter. You just need to create bytearrayoutputstream or Chararraywriter to write the data, just like you write other streams. When all the data is written, all the data written will be returned as an array whenever Tobytearray () or ToCharArray is called.

Examples are as follows:

1 OutputStream output = newByteArrayOutputStream();
2
3  
4
5 output.write("This text is converted to bytes".toBytes("UTF-8"));
6
7  
8
9 byte[] bytes = output.toByteArray();

An array of uppercase characters is similar to this example. Just wrap the character array on the Chararraywriter.

Java IO Learning--(v) byte and character array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.