Is there a way to use FileOutputStream in a way that if a file (String filename) does not exist, then it will create it?
FileOutputStream oFile = new FileOutputStream("score.txt", false);
Is there a way to use FileOutputStream in a way that if a file (String filename) does not exist, then it will create it?
FileOutputStream oFile = new FileOutputStream("score.txt", false);
You can potentially get a
FileNotFoundException
if the file does not exist.Java documentation says:
If you're using Java 7 you can use the java.nio package:
Pass this
f
to yourFileOutputStream
constructor.It will throw a
FileNotFoundException
if the file doesn't exist and cannot be created (doc), but it will create it if it can. To be sure you probably should first test that the file exists before you create theFileOutputStream
(and create withcreateNewFile()
if it doesn't):FileUtils from apache commons is a pretty good way to achieve this in a single line.
This will create parent folders if do not exist and create a file if not exists and throw a exception if file object is a directory or cannot be written to. This is equivalent to:
All the above operations will throw an exception if the current user is not permitted to do the operation.
Before creating a file, it's needed to create all the parent directories.
Use
yourFile.getParentFile().mkdirs()
Create file if not exist. If file exits, clear its content: