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:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
/**
* @author Pokidov.Dmitry
* Date: 13.04.2009
*/
public class IOHelper {
/*Block size that we want to read in one time.*/
private static final int READ_BLOCK = 8192;
/*
* Read all from stream, using nio.
* @param is source stream.
* @return result byte array that read from source
* @throws IOException by {@code Channel.read()}
*/
public static byte[] readToEnd(InputStream is) throws IOException {
//create channel for input stream
ReadableByteChannel bc = Channels.newChannel(is);
ByteBuffer bb = ByteBuffer.allocate(READ_BLOCK);
while (bc.read(bb) != -1) {
bb = resizeBuffer(bb); //get new buffer for read
}
byte[] result = new byte[bb.position()];
bb.position(0);
bb.get(result);
return result;
}
private static ByteBuffer resizeBuffer(ByteBuffer in) {
ByteBuffer result = in;
if (in.remaining() < READ_BLOCK) {
//create new buffer
result = ByteBuffer.allocate(in.capacity() * 2);
//set limit to current position in buffer and set position to zero.
in.flip();
//put original buffer to new buffer
result.put(in);
}
return result;
}
Also I found an interesting book in which you can read about the nio package: get it here
Комментариев нет:
Отправить комментарий