Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java.io.File.length() returns 0

Tags:

java

file

I'm doing a applet for ftp file transfers and I need to know the size of a local file (for download resumes). The problem is the File.length() returns 0.

The file exists (checked with File.exists()), and has more than 0 bytes (in Windows at least).

I don't know where more to look to find out why length() is returning 0.

Here is part of the code and the result.

long fileOffset = 0;

if(localfile.exists()){
    fileOffset = localfile.length();
    System.out.println("The file " + localfile.getAbsolutePath() + " has " + localfile.length() +" in size");
    System.out.println("Resume at: " + fileOffset);
    outputStream.skip(fileOffset);
    ftp.setRestartOffset(fileOffset);
    count = fileOffset;
}

And the result in the console is:

The file D:\test\About Downloads.pdf has 0 in size
Resume at: 0

Thanks

like image 709
Proença Avatar asked Aug 05 '11 20:08

Proença


2 Answers

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.

like image 141
Michael Berry Avatar answered Nov 06 '22 20:11

Michael Berry


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?

like image 41
Ernest Friedman-Hill Avatar answered Nov 06 '22 19:11

Ernest Friedman-Hill