I would suggest the following for Java8+.
/**
* Creates a File if the file does not exist, or returns a
* reference to the File if it already exists.
*/
private File createOrRetrieve(final String target) throws IOException{
final Path path = Paths.get(target);
if(Files.notExists(path)){
LOG.info("Target file \"" + target + "\" will be created.");
return Files.createFile(Files.createDirectories(path)).toFile();
}
LOG.info("Target file \"" + target + "\" will be retrieved.");
return path.toFile();
}
/**
* Deletes the target if it exists then creates a new empty file.
*/
private File createOrReplaceFileAndDirectories(final String target) throws IOException{
final Path path = Paths.get(target);
// Create only if it does not exist already
Files.walk(path)
.filter(p -> Files.exists(p))
.sorted(Comparator.reverseOrder())
.peek(p -> LOG.info("Deleted existing file or directory \"" + p + "\"."))
.forEach(p -> {
try{
Files.createFile(Files.createDirectories(p));
}
catch(IOException e){
throw new IllegalStateException(e);
}
});
LOG.info("Target file \"" + target + "\" will be created.");
return Files.createFile(
Files.createDirectories(path)
).toFile();
}