Showing posts with label files. Show all posts
Showing posts with label files. Show all posts

Java FileOutputStream Create File or Parent Folders if not exists

FileUtils from apache commons is a pretty good way to achieve this in a single line.
FileOutputStream s = FileUtils.openOutputStream("/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.