views:

320

answers:

1

Does anybody know a good way to find the file size that is dynamically loaded by urlclassloader?

I am using the urlclassloader in the following manner, but need to keep track of how much bandwidth is being used.

URLClassLoader sysloader = (URLClassLoader) ClassLoader
   .getSystemClassLoader();
Class<URLClassLoader> sysclass = URLClassLoader.class;
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, (Object[]) urls);

Thanks in advance!

A: 

If you know the urls being loaded are http urls, and you can ensure the server they're on returns a Content-Length header, you can get their size with the following:

public static int getContentLength (URL url)
    throws IOException
{
    String contentLength = url.openConnection().getHeaderField("Content-Length");
    if (contentLength == null) {
        throw new IllegalArgumentException(url + " didn't have a "
            + "Content-Length header");
    } else {
        return Integer.parseInt(contentLength);
    }
}
Charlie Groves