• Post Reply Bookmark Topic Watch Topic
  • New Topic

getContentLength

 
Mohammad Farhat
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys,
i am trying to get to know the length of the stream i will be reading, so i simply created a URLConnetion instance, and issued on it URLConnection.openConnection().getContentLength()
when running this code from my machine, it worked, yet when i placed the code on the server, and tried accessing it using my applet (the code is written inside an applet), it returned -1, meaning that (according to Java docs,) the length cannot be known yet.
So are there better ways to do this? knowing that my whole purpose is to read the whole stream at once, and to do that in the most optimal and fast way, and i've tried to do that using the following code(but when it returned -1, this method failed):

urlConn = new URL(imgURL);
System.out.println("before streams time:"+(new java.util.Date()));
URLConnection conn = urlConn.openConnection();
inputStream = conn.getInputStream();
int imageSize = conn.getContentLength();
inS = new BufferedInputStream(inputStream);
inS.mark(imageSize+1);
din = new DataInputStream(inS);
din.mark(imageSize+1);
byte[] myTempArray = new byte[imageSize];
din.readFully(myTempArray);

thanks guys,
Mohammad
 
Joe Ess
Bartender
Posts: 9361
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't neet to know the content length beforehand. Use a ByteArrayOutputStream to accumulate the bytes as you read them in. If you are concerned about performance either use a BufferedInputStream to read blocks of data for you or do it yourself with InputStream.read(byte[]).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!