Java FileOutputStream Create File if not exists
FileUtils from apache commons is a pretty good way to achieve this in a single line.
FileOutputStream s = FileUtils.openOutputStream(new File("/home/nikhil/somedir/file.txt"))
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:
File file = new File("/home/nikhil/somedir/file.txt");
file.getParentFile().mkdirs(); // Will create parent directories if not exists
file.createNewFile();
FileOutputStream s = new FileOutputStream(file,false);
All the above operations will throw an exception if the current user is not permitted to do the operation.
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 the FileOutputStream
(and create with createNewFile()
if it doesn't):
File yourFile = new File("score.txt");
yourFile.createNewFile(); // if file already exists will do nothing
FileOutputStream oFile = new FileOutputStream(yourFile, false);
Before creating a file, it's necessary to create all parent directories.
Use yourFile.getParentFile().mkdirs()
Update: Create all parent folders only when they are not already exist. Otherwise it is not necessary.