Lately I've faced a simple problem: I needed to read all bytes from the InputStream. I didn't know type of the InputStream, so, I've spent more then two hours solving this problem without any success. I didn't want to read each byte from the stream. All evening I could think only about this problem. Solution turned to be very simple! I found a sample in the JDK installation directory($JAVA_HOME/sample/nio/). JDK 1.5(and higher) is a good API to work with streams over channels. The source code to read all bytes from the InputStream is rather simple:
- private static final int READ_BLOCK = 8192; //Block size that we want to read in one time.
- private ByteBuffer resizeBuffer(ByteBuffer in) {
- ByteBuffer result = in;
- if (in.remaining() < READ_BLOCK) {
- result = ByteBuffer.allocate(in.capacity() * 2); //create new buffer
- in.flip(); //set limit to current position in buffer and set position to zero.
- result.put(in); //put original buffer to new buffer
- }
- return result;
- }
- private byte[] readAllFromInputStream(InputStream is) throws IOException {
- ReadableByteChannel bc = Channels.newChannel(is); //create channel for input stream
- ByteBuffer bb = ByteBuffer.allocate(READ_BLOCK);
- while (bc.read(bb) != -1) {
- bb = resizeBuffer(bb); //get new buffer for read
- }
- bb.flip();
- return bb.array();
- }
Also I found an interesting book in which you can read about the nio package: get it here

0 коммент.:
Отправить комментарий