File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Why Does a Non-existent File Have a Length of Zero? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why Does a Non-existent File Have a Length of Zero?" Watch "Why Does a Non-existent File Have a Length of Zero?" New topic
Author

Why Does a Non-existent File Have a Length of Zero?

Kevin Simonson
Ranch Hand

Joined: Oct 22, 2011
Posts: 114
I realize that the Java documentation kind of hints that non-existent files might be considered to have a length of zero. In my own case I wrote the following code:

and when I ran it on a non-existent file it did indeed give me a length of zero for the file, before the next line threw an exception, so my own application considers a non-existent file to have length zero. But does anybody know why it was chosen for such a file to have length zero? Why didn't my call to the {length()} method for object {ntFile} throw a {FileNotFoundException} itself?

KevinSim
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

I would guess they did it that way to avoid having to make extra calls in the more common cases. If we're calling length(), then it's one of the following cases:

  • We already know the file exists, so no point in forcing us to make an extra call to test for existence or to catch an exception.
  • We're not going to do anything with an empty file, so no point in forcing us to make an extra call to test for existence or to catch an exception.
  • We're going to try accessing the file, even if it's empty. We'll have to handle the exception at that point anyway, so nothing gained by throwing it at the length check.


  • In short, there's nothing to be gained by throwing an exception, and possibly some extra work to be added that we don't have to do now.
    Jesper de Jong
    Java Cowboy
    Saloon Keeper

    Joined: Aug 16, 2005
    Posts: 14430
        
      23

    Note that class File also has an exists() method, that may be an easier way to check if a file exists than trying to open it and catch FileNotFoundException.


    Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Why Does a Non-existent File Have a Length of Zero?