Java.io.File.length() returns 0

Viewed 17820

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

6 Answers

There are sometimes OS issues in returning file size accurately, even when the file is quite stable. I adopted a two fold approach of using File and NIO if File failed

     long discoveredFileLength = discoveredFile.length();
    if (discoveredFileLength == 0) {
        final Path discoveredFilePath = Paths.get(discoveredFile.getAbsolutePath());
        FileChannel discoveredFileChannel = null;
        try {
            discoveredFileChannel = FileChannel.open(discoveredFilePath);
            discoveredFileLength = discoveredFileChannel.size();
        }
        catch (IOException e2) {
        }
    }

    if (discoveredFileLength <= 0) {
        logErrors(discoveredFile.getName() + " " + discoveredFileLength  + " COULD NOT BE PROCESSED (length <= 0)");
        _reporter.increaseFilesFailed();
        return;
    }
Related