...
| Code Block | ||||
|---|---|---|---|---|
| ||||
public void fio54openFile_nce1nce(String filename) throws FileNotFoundException{ OutputStream out = new FileOutputStream(filename); // Work with FILE } |
If the file existed before being opened, its former contents will be overwritten with the contents provided by the program.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
public void fio54noOverwrite_nce2nce(String filename) throws FileNotFoundException{ OutputStream out = new FileOutputStream(filename, true); // Work with FILE } |
If the file existed before being opened, its new contents will be appended to the former contents. This code is compliant only if this was the intention of the programmer.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
public void fio54noAlter_nce3nce(String filename) throws FileNotFoundException{ OutputStream out = new FileOutputStream(filename, true); if (!new File(filename).createNewFile()) { // File cannot be created...handle error } else { OutputStream out = new FileOutputStream(filename); // Work with FILE } } |
Unfortunately, this solution is subject to a TOCTOU (time-of-check-time-of-use) race condition. It is possible for an attacker to modify the file system such that the file that is created is not the file that is opened.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
public void fio54createFile_cs(String filename) throws FileNotFoundException{ try (OutputStream out = new BufferedOutputStream( Files.newOutputStream( Paths.get(filename), StandardOpenOption.CREATE_NEW))) { // Work with out } catch (IOException x) { // File not writable...handle error } } |
Applicability
The ability to determine if an existing file has been opened or a new file has been created provides greater assurance that a file other than the intended file is not opened or overwritten.
...