• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Java API createNewFile() returns false

 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

The Java API createNewFile returns false in one of the environment and not sure about the reasons

Is there is any logger can be enabled to find out the reason ?

Why can't java provide another API which throws exception instead of returning false

Please advise.

Thanks
 
Rancher
Posts: 144
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because using Exceptions as controll flow isn't how they should be used. If you get a false from createNewFile() whatever it was you wanted can't be created. This can have three reasons:
1) illegal path
2) target already exists
3) no permissions
For 2 and 3 there're several other methods you can use to check before calling createNewFile() and it's your response as the dev to correctly use them - not of the API to throw an Exception to hint you made a mistake. About 1: always use "/" instead of "\\" as Java does the translation for you - stick to ASCII (more specific: a-zA-Z0-9) and don't use spaces - should solve "illegal" paths
 
Bartender
Posts: 2237
63
IntelliJ IDE Firefox Browser Spring Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From javadoc:

javadoc wrote:Returns:
   true if the named file does not exist and was successfully created; false if the named file already exists


And the method does throw exceptions:

javadoc wrote:Throws:
   IOException - If an I/O error occurred
   SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file

 
Sheriff
Posts: 22850
132
Eclipse IDE Spring Chrome Java Windows
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Johnny Joseph wrote:Why can't java provide another API which throws exception instead of returning false


There is. java.io.File is quite old, and parts of its API are terrible. Methods returning false without any more information, list methods returning null instead of throwing exceptions, etc. Fortunately, in Java 7 Path was introduced. Besides making it possible to provide multiple file system implementations (including non-local file systems), a lot of the methods throw proper exceptions instead. There is one caveat however - you often shouldn't look what methods Path itself has, but instead resort to utility class Files. For instance: Files.createFile will create the file, throwing a FileAlreadyExistsException if the file already exists.
 
Johnny Joseph
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The problem occured due to permissions..However not shown any error and returned just false......That's the problem..Is there a way to identify the permission before hand i.e before using createNewFile()...Is there is any Java API to check for permissions and display the required permission with name doesn't exist.
 
Kristina Hansen
Rancher
Posts: 144
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Rob Spoor wrote:

Johnny Joseph wrote:Why can't java provide another API which throws exception instead of returning false


There is. java.io.File is quite old, and parts of its API are terrible. Methods returning false without any more information, list methods returning null instead of throwing exceptions, etc. Fortunately, in Java 7 Path was introduced. Besides making it possible to provide multiple file system implementations (including non-local file systems), a lot of the methods throw proper exceptions instead. There is one caveat however - you often shouldn't look what methods Path itself has, but instead resort to utility class Files. For instance: Files.createFile will create the file, throwing a FileAlreadyExistsException if the file already exists.


That's bad design as it uses Exceptions for control flow - wich shouldn't be used in that way.

Johnny Joseph wrote:The problem occured due to permissions..However not shown any error and returned just false......That's the problem..Is there a way to identify the permission before hand i.e before using createNewFile()...Is there is any Java API to check for permissions and display the required permission with name doesn't exist.


Yes, there are - several in fact.
Have a look: https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/io/File.html
canRead()
canWrite()
canExecute()
exists()
isDirectory()
isFile()
isHidden()
Basically any method that returns a boolean can be used to correctly check upfront if what you want to create already exist or if you even have rights to do what you want to do. As said in my first reply: It's up to you as the dev correctly use those provided methods to check upfront instead of rely on useful returns or mis-used exceptions.
 
Master Rancher
Posts: 5172
83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Kristina Hansen wrote:That's bad design as it uses Exceptions for control flow - wich shouldn't be used in that way.



That seems a bit... extreme, I think.  Fundamentally, throwing an exception is always a form of control flow, combined with an object designed to pass along useful information.  We are advised to use them only for "exceptional" cases, not routine situations.  But it can be pretty subjective, to decide what is routine and what isn't.  It depends on the use case, the environment, and even the type of end user you are writing for.  Sometimes we need to carefully consider all the things that might go wrong, and make sure we have strategies for handling them without bothering anyone else.  And sometimes it's perfectly acceptable to just handle the expected situation, and if something goes wrong, send the user a nice clear message explaining what that was.  Personally I find the latter case extremely common, and I find exceptions to often be a good way to do that.  I usually write internal applications, where my end users (including myself) are perfectly happy seeing a stack trace identifying a problem - they just hate for it to fail silently.  I can (and have) written code to check all the reasons why a file operation might fail - at least, all that I can possibly check - and yet, most if the time, it's much much simpler to just call a single simple method to "just do it" and tell me if there was a problem.  So I'm quite happy they devised the new NIO2 Files methods to handle what I previously had to write many more lines of code for.
 
Kristina Hansen
Rancher
Posts: 144
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Valid points - but in java.io File handling in particular for me is flawed if you look at the other "discusion" about "Errors, checked Exceptions and unchecked Exceptions" - IDK if you read it, but for short: for me unchecked Exceptions are all what the programmer has to account for upfront to let it happen - or to say it the other way around: if an unchecked Exception is thrown the programmer did something wrong and should rework the code. So for me, a FileNotFoundException should be a RuntimeException as the dev has several methods upfront to check if the file exists and if it can be accessed - but as it is an IOException for me that's flawed - cause this can only happen if something happens between the File.exists() call and the actual access - wich is often such a tiny time frame window it's often only abused by crackers to power glitch the clock to bypass security - wich shouldn't affect java anyway. But I guess that goes to far off top as the topic itself was answered by one of the most typical reasons: "missing permissions". In that case false make sense as true is only returned if and only if the file could had been created successfully. And to create a file on most modern systems you need write access to the folder you want to create a file in. So, when a createFile returns false the two logical options: does it already exists from an earlier run or does the process have rights to create one - and if you go really low-level that's actually how the "error" is caused in the first place: before the OS tries to create the file it checks if the current user has write permissions on the directory. So why not do the same: check write permission before try to write (create the file)?
 
Rob Spoor
Sheriff
Posts: 22850
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Kristina Hansen wrote:That's bad design as it uses Exceptions for control flow - wich shouldn't be used in that way.


But you can check first, using Files.exists. The only downside there is that the check and creation are not atomic.

Kristina Hansen wrote:Yes, there are - several in fact.
Have a look: https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/io/File.html
canRead()
canWrite()
canExecute()
exists()
isDirectory()
isFile()
isHidden()


And the NIO2 equivalents:
* Files.isReadable(Path)
* Files.isWritable(Path)
* Files.isExecutable(Path)
* Files.exists(Path)
* Files.isDirectory(Path). By default it will follow links but this can be disabled by providing LinkOption.NOFOLLOW_LINKS.
* Files.isRegularFile(Path). Again, links are followed by default.
* Files.isHidden(Path)
 
Mike Simmons
Master Rancher
Posts: 5172
83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Rob Spoor wrote:

Kristina Hansen wrote:That's bad design as it uses Exceptions for control flow - wich shouldn't be used in that way.


But you can check first, using Files.exists. The only downside there is that the check and creation are not atomic.



I would say you need to make sure the parent directory exists, and that it's really a directory, and that it's writeable, and that the file does not already exist.  And yes, hope that none of that will change before you create the file.  
 
Rancher
Posts: 4801
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Kristina Hansen wrote:So for me, a FileNotFoundException should be a RuntimeException as the dev has several methods upfront to check if the file exists and if it can be accessed - but as it is an IOException for me that's flawed - cause this can only happen if something happens between the File.exists() call and the actual access - wich is often such a tiny time frame window...



However it's still a valid fail point that will need to be checked.  In other words you still need to handle the case where the file already exists, only now you're handling it twice.
In a multi-threaded environment (which is most of the ones we deal with in Java) the odds increase as load increases.

To me this is the equivalent of the common JDBC question, where people write SQL to check if a row exists before doing the insert.  It's pointless, as you still have to handle the situation where another thread has inserted the row between your check and the actual insert.  May as well just deal with it the once, where the exception is thrown.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic