Hi All,

I have come across Read and write method from InputStream and outputstream but im finding it hard to understand the logic behind it.

Below is a simple example which reads a jar file from input stream and writes it to output stream. Please explain the logic on how this reading and writing happens .

** Please assume other parameters in below code are defined/intialised properly **

InputStream is = ctx.getResourceAsStream("/bookcode.jar");

int read = 0;

byte[] bytes = new byte[1024];

OutputStream os = response.getOutputStream();

while((read = is.read(bytes) != -1) {


os.write(bytes,0,read);



}

os.flush();
os.close();

}

** what will happen when i change bytes size to something other than 1024 for example 20 or 30... and
What is happening in while condition statement and body ?

Thanks in advance

Recommended Answers

All 3 Replies

is.read(bytes) reads some number of bytes into the array, then returns an int with the number of bytes actually read. That value is assigned to the variable read. Depending on the type of stream that may be a complete array-full of bytes, or some smaller number, or even, in theory, zero.

When the read() is at end of file it (obviously) doesn't read any bytes into the array, and returns a value of -1 to indicate eof. Thw while test tests for a -1 being returned, and stops looping when that happens.

eg Suppose yo have 300 bytes in a file, and a buffer size of 255
First read reads 255 bytes, returns 255, loop continues
Second read reads remaining 45 brtes, returns 45, loop continues
Third read is now at eof, reads no bytes, returns -1. Loop exits

Hi James,

excuse me for late response, no net connection.

when you said "eg Suppose you have 300 bytes in a file, and a buffer size of 255".

is buffer size is what we mention in the size of array i mean i decalred byte array of 1024, so is that the buffer size ?

Yes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.