javadoc wrote:Returns:
true if the named file does not exist and was successfully created; false if the named file already exists
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
Johnny Joseph wrote:Why can't java provide another API which throws exception instead of returning false
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
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.
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.
Kristina Hansen wrote:That's bad design as it uses Exceptions for control flow - wich shouldn't be used in that way.
Kristina Hansen wrote:That's bad design as it uses Exceptions for control flow - wich shouldn't be used in that way.
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()
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.
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...
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |