Java.io.File.length() returns 0

You probably don't have enough permissions to access the file at all...

  1. Try signing your applet. (Even self-signed certificate will do.)
  2. While developing, you can modify the Java security policy to allow accessing local files: see %JRE_HOME%/lib/security/java.policy, try adding

    permission java.io.FilePermission "<<ALL FILES>>", "read,write";

  3. Try using the new JNLP API to access local files (Java5 only though...)


The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist. Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes.


The existence of the variable "outputStream" suggests that at this point, perhaps you've already opened the file for writing, and in the process, you've truncated it. Try computing the size before actually opening the file?


There's no reason in that code that I can see why it should return 0 if it's not empty, are you doing anything elsewhere with that file?

If you've got the file open somewhere else, or are writing to it and call length before you've flushed the writer (this could be in Java or elsewhere) then it may return 0. If you close and flush all writers to that file before checking its length and you may have a different result.

Tags:

Java

File