Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Kevin Simonson
Ranch Hand
Posts: 219
2
  • Mark post as helpful
  • send pies
  • 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
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • 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.
     
    Jesper de Jong
    Java Cowboy
    Sheriff
    Posts: 16028
    87
    Android IntelliJ IDE Java Scala Spring
    • Mark post as helpful
    • send pies
    • 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.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!