Java FileOutputStream Create File if not exists Java FileOutputStream Create File if not exists java java

Java FileOutputStream Create File if not exists


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 exist. Otherwise it is not necessary.


You can create an empty file whether it exists or not ...

new FileOutputStream("score.txt", false).close();

if you want to leave the file if it exists ...

new FileOutputStream("score.txt", true).close();

You will only get a FileNotFoundException if you try to create the file in a directory which doesn't exist.