• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 246
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
     
    Java Cowboy
    Posts: 16084
    88
    Android Scala IntelliJ IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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.
     
    Don't get me started about those stupid light bulbs.
    reply
      Bookmark Topic Watch Topic
    • New Topic