ByteArrayOutputStream
In this chapter you will learn:
- How to use ByteArrayOutputStream
- How to use ByteArrayOutputStream to store byte array
- How to get byte array from ByteArrayOutputStream
Use ByteArrayOutputStream
java.lang.Object
|
+java.io.OutputStream
|
+-java.io.ByteArrayOutputStream
ByteArrayOutputStream
is an implementation of
OutputStream
that uses a byte array as the destination.
ByteArrayOutputStream
has two constructors, shown here:
ByteArrayOutputStream( )
a buffer of 32 bytes is created.ByteArrayOutputStream(int numBytes)
a numBytes-sized buffer
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/* j av a 2 s . co m*/
public class Main {
public static void main(String args[]) throws IOException {
ByteArrayOutputStream f = new ByteArrayOutputStream();
byte buf[] = "this is a test".getBytes();
f.write(buf);
System.out.println(f.toString());
byte b[] = f.toByteArray();
for (int i = 0; i < b.length; i++) {
System.out.println((char) b[i]);
}
OutputStream f2 = new FileOutputStream("test.txt");
f.writeTo(f2);
f2.close();
f.reset();
for (int i = 0; i < 3; i++){
f.write('X');
}
System.out.println(f.toString());
}
}
Store byte array
We can write string value to a ByteArrayOutputStream
by converting
them to byte array. The following code converts the string value
to byte array using default system encoding.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
//from j ava 2 s . com
public class Main {
public static void main(String args[]) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
outStream.write('a');
outStream.write(("java2s.com").getBytes());
System.out.println("outstream: " + outStream);
System.out.println("size: " + outStream.size());
outStream.close();
}
}
The output:
outstream: ajava2s.com
size: 11
Get byte array from ByteArrayOutputStream
The following code creates a ByteArrayOutputStream
and
store value in it. Then it get the byte array out of ByteArrayOutputStream
and print them out.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
/*from ja v a 2 s.c o m*/
public class Main {
public static void main(String args[]) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
outStream.write('a');
outStream.write(("java2s.com").getBytes());
System.out.println(Arrays.toString(outStream.toByteArray()));
System.out.println(new String(outStream.toByteArray()));
outStream.close();
}
}
The output:
[97, 106, 97, 118, 97, 50, 115, 46, 99, 111, 109]
ajava2s.com
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » I/O