Missing check on the result of createNewFile Info

The result of createNewFile should be checked. createNewFile returns false if the named file already exists and a new file is not created. If your code misses a check on the result of createNewFile, you might silently overwrite an existing file leading to data loss.

Detector ID
java/missing-check-on-createnewfile@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public File createFileNonCompliant(File outputFolder, final String fileName) throws IOException {
2    File file = new File(outputFolder, fileName);
3    // Noncompliant: does not check if createNewFile succeeded or failed.
4    file.createNewFile();
5    return file;
6}

Compliant example

1public Optional<File> createFileCompliant(File outputFolder, final String fileName) throws IOException {
2    File file = new File(outputFolder, fileName);
3    // Compliant: handles the case when createNewFile fails.
4    if (!file.createNewFile()) {
5        log.debug("File already exists, using existing file " + file.getAbsolutePath() + ".");
6        return Optional.empty();
7    }
8    return Optional.of(file);
9}