This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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: 103
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: 14074
        
      16

    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 7 API documentation
    Scala Notes - My blog about Scala
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Why Does a Non-existent File Have a Length of Zero?
     
    Similar Threads
    Using JSON with Java
    Find the Beginging Position of a Field With Pipe Delimeter
    Send content of file over tcp socket
    Bizarre Incompatible Types Complaint
    Inheriting two Fields with the same Name