Issac already answered this correctly, but I'll have a go as well.

>Following is the relevant code i'm using. There may
>be syntax errors as i haven't run the code.. I just need
>to know a method of reading a gif properly.

First, why are you doing this? Can't you use the default servlet
somehow to serve content?


Now, on with the code critique:

>res.setContentType("image/gif");
>PrintWriter toClient = res.getWriter();

This is your first problem, the PrintWriter is only to be used for
text output.


>toClient.println(readfile("/path.to/image.gif"));

This is your second problem. Why are you reading a GIF file into a
String? That won't work because a String is for text and a GIF file
isn't text.

Anyway, it's a bad idea because of the peformance hit of reading the
whole GIF file into memory at once, what if the GIF file were 1000Kb?


>toClient.close();

>public String readfile(String infilepath) {
>  InputStream inf = new FileInputStream(infilepath);
>  BufferedInputStream bin = new BufferedInputStream(inf);
>  int len = bin.available();

This is another problem, available() reports what is in a buffer and
that's not necessarily the same as the size of the file.


Here's some code that works for either text files or binary files:

{
  response.setContentType(whatever);
  OutputStream out=response.getOutputStream();
  FileInputStream fin=new FileInputStream(fname);
  byte[] buf=new byte[5000];
  int red=fin.read(buf,0,5000);
  while(red>-1)
  {
     out.write(buf,0,red);
     red=find.read(buf,0,5000);
  }
  out.close();
}


This is efficient. It reads the file in blocks and writes the block
out before continuing. It understands the available() call properly.
It also handles text or binary data.


Nic

___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".

Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html

Reply via email to