Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Read file from a remote place

843785Dec 23 2008 — edited Dec 24 2008
URL url = new URL("http://www.someurl.com");
URLConnection conn = url.openConnection();

InputStream in = conn.getInputStream();

// allocate enough space for a whole file
byte[] buffer = new byte[conn.getContentLength()];

in.read(buffer);
in.close();
        
return new String(buffer, "UTF8");
works really good. Reads most of the files in less than a second.
There is only one problem - not all websites return getContentLenght(). For some sites it's -1

so what is the right way to find the size of the file before reading it? I need to know the exact size so I can allocate the right amount of bytes in a byte array.

if it's not possible, is there a better way to read remote file into string?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 21 2009
Added on Dec 23 2008
14 comments
253 views