This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

getContentLength  RSS feed

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);
din = new DataInputStream(inS);
byte[] myTempArray = new byte[imageSize];

thanks guys,
Joe Ess
Posts: 9406
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[]).
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!