I am running a java application from a jar file. How can I get the size of that file?
Also, how can I get the size of a file from the internet without actually downloading it?
Eventually, I am just going to download the files if they are different sizes, i.e. creating an auto update.
Also, how would this work in the IDE where there is no jar file?
Edit: I need to read a remote file's size anyway for other reasons, so would be nice to know even if it is not the best way.
It seems your real goal is to create an auto-updating application. Every Java SE installation comes with Java Web Start, which automatically handles this, including checking your application .jar file's date and downloading it if necessary.
To turn your application into a Java Web Start application is easy. Your code doesn't need to change at all. The web server which hosts your .jar file should also host a short XML file with a .jnlp
extension. That file tells Java the .jar file's location, the application's full name, and the minimum version of Java needed to run the application. It can do many other things, including installing itself into the user's Start menu (or the equivalent in Linux and OS X). All of these things are automatically handled when a user elects to run your application, which they do by simply clicking on a hyperlink to your .jnlp file.
The Java Web Start tutorial is here.
A basic .jnlp file might look like this:
<?xml version="1.0"?>
<!DOCTYPE jnlp PUBLIC "-//Sun Microsystems, Inc//DTD JNLP Descriptor 6.0.10//EN" "http://java.sun.com/dtd/JNLP-6.0.10.dtd">
<jnlp version="1.6"
codebase="http://www.example.com/myapp/"
href="MyApp.jnlp">
<information>
<title>MyApp</title>
<vendor>ExampleCo Inc.</vendor>
<homepage href="http://www.example.com/myapp/index.html"/>
<description>The greatest application ever.</description>
<icon kind="default" href="myapp48x48.gif"/>
<offline-allowed/>
</information>
<security>
<all-permissions/>
</security>
<resources>
<j2se version="1.7+"/>
<jar href="MyApp.jar" main="true"/>
</resources>
<application-desc/>
</jnlp>
To address your original question: Java Web Start seems to decide whether to update a file based on the file's server timestamp, much like web browsers do, so if I were going to do it manually (which I wouldn't, because Java Web Start does it much better), I'd use an HTTP HEAD request to read the headers without downloading the file:
boolean isDownloadNeeded(URL url,
Path cachedFile)
throws IOException {
if (Files.notExists(cachedFile)) {
return true;
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
long serverTimestamp = conn.getLastModified();
long fileTimestamp = Files.getLastModifiedTime(cachedFile).toMillis();
return (serverTimestamp == 0 || fileTimestamp < serverTimestamp);
}