Java Reference
In-Depth Information
}
} catch (IOException e) {
// Handle error
}
}
Unfortunately, the Java API lacks any guarantee that the isSameFile() method actu-
ally checks whether the files are the same file. The Java 7 API for isSameFile() [API
2013] says:
If both Path objects are equal then this method returns true without checking if the
file exists.
That is, isSameFile() may simply check that the paths to the two files are the same
and cannot detect if the file at that path had been replaced by a different file between the
two open operations.
Compliant Solution (Multiple Attributes)
Thiscompliantsolutionchecksthecreationandlast-modifiedtimesofthefilestoincrease
the likelihood that the file opened for reading is the same file that was written:
Click here to view code image
public void processFile(String filename) throws IOException{
// Identify a file by its path
Path file1 = Paths.get(filename);
BasicFileAttributes attr1 =
Files.readAttributes(file1, BasicFileAttributes.class);
FileTime creation1 = attr1.creationTime();
FileTime modified1 = attr1.lastModifiedTime();
// Open the file for writing
try (BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(Files.newOutputStream(file1)))) {
// Write to file...
} catch (IOException e) {
// Handle error
}
// Reopen the file for reading
Path file2 = Paths.get(filename);
BasicFileAttributes attr2 =
Files.readAttributes(file2, BasicFileAttributes.class);
FileTime creation2 = attr2.creationTime();
Search WWH ::




Custom Search