Java FileOutputStream Create File if not exists

Stefan Dunn picture Stefan Dunn · Mar 8, 2012 · Viewed 379.9k times · Source

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);

Answer

talnicolas picture talnicolas · Mar 8, 2012

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);