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 = new byte [ 1024 ]; |
09 |
InputStream input = new ByteArrayInputStream(bytes); |
15 |
int data = input.read(); |
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 = new ByteArrayOutputStream(); |
5 |
output.write( "This text is converted to bytes" .toBytes( "UTF-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