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?