Java IO: Byte & Char Arrays

Jakob Jenkov
Last update: 2015-08-29

Byte and char arrays are often used in Java to temporarily store data internally in an application. As such arrays are also a common source or destination of data. You may also prefer to load a file into an array, if you need to access the contents of that file a lot while the program is running. Of course you can access these arrays directly by indexing into them. But what if you have a component that is designed to read some specific data from an InputStream or Reader and not an array?

Reading Arrays via InputStream or Reader

To make such a component read from the data from an array, you will have to wrap the byte or char array in an ByteArrayInputStream or CharArrayReader. This way the bytes or chars available in the array can be read through the wrapping stream or reader.

Here is a simple example:

byte[] bytes = new byte[1024];

//write data into byte array...

InputStream input = new ByteArrayInputStream(bytes);

//read first byte
int data = input.read();
while(data != -1) {
    //do something with data

    //read next byte
    data = input.read();
}

To do the same with a char array is pretty analogous to this example. Just wrap the char array in a CharArrayReader and you are good to go.

Writing to Arrays via OutputStream or Writer

It is also possible to write data to an ByteArrayOutputStream or CharArrayWriter. All you have to do is to create either a ByteArrayOutputStream or CharArrayWriter, and write your data to it, as you would to any other stream or writer. Once all the data is written to it, simply call the method toByteArray() or toCharArray, and all the data written is returned in array form.

Here is a simple example:

ByteArrayOutputStream output = new ByteArrayOutputStream();

output.write("This text is converted to bytes".getBytes("UTF-8"));

byte[] bytes = output.toByteArray();

To do the same with a char array is pretty analogous to this example. Just wrap the char array in a CharArrayWriter and you are good to go.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next