servlet to display image not working randomly

Hi, all

I use a servlet to read different png file into byte[] according request, then I send it to browser client. Here is the code:

code

os=response.getOutputStream();

byte[] rawPNG=null;

try {

String imagePath=<image location>

FileInputStream fis=new FileInputStream(imagePath);

int imageSize=fis.available();

rawPNG=new byte[imageSize];

int offset=0,counter=0;

while ( offset < imageSize ) {

counter=fis.read(rawPNG,offset,imageSize-offset);

offset+=counter;

//System.out.println("size="+imageSize+",offset="+offset+",read="+counter);

}

fis.close();

} catch (Exception e) {

// read image error

}

try {

sr.setContentType("image/png");

sr.setContentLength(rawPNG.length);

os.write(rawPNG);

os.flush();

//os.close();

} catch (Exception e) {

// send image error

}

code

Usually, 4 correct images returned in 5 request. No exception observed. Why this servlet failed randomly? I don't have a clue.

BTW: If I uncomment 'os.close();' line, I got 'java.io.Excepiton: Closed' error message. Why it happends?

Thanks,

Vincent Chen

[1247 byte] By [VC@TWa] at [2007-10-2 13:40:29]
# 1

Why don't you try printing the stack trace when you get an exception instead of doing nothing there?

I'm guessing the other thing - you getting the 'java.io.Excepiton: Closed' is because the response output stream will be automatically closed by the servlet container when your service method is done. So you don't need to do it yourself

somaiaha at 2007-7-13 11:33:18 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...