Java Reference
In-Depth Information
Compliant Solution ( RandomAccessFile )
A better approach is to avoid reopening files. The following compliant solution demon-
strates use of a RandomAccessFile , which can be opened for both reading and writing.
Becausethefileisonlyclosedautomatically bythe try -with-resourcesstatement, norace
condition can occur. Note that this compliant solution and others use the readLine()
method for illustrative purposes, but see “MSC05-J. Do not exhaust heap space” [Long
2012] for more information about possible weaknesses of this method.
Click here to view code image
public void processFile(String filename) throws IOException{
// Identify a file by its path
try ( RandomAccessFile file = new
RandomAccessFile(filename, "rw")) {
// Write to file...
// Go back to beginning and read contents
file.seek(0);
String line;
while ((line = file.readLine()) != null) {
System.out.println(line);
}
}
}
Noncompliant Code Example (File Size)
Thisnoncompliantcodeexampletriestoensurethatthefileitopenscontainsexactly1024
bytes:
Click here to view code image
static long goodSize = 1024;
public void doSomethingWithFile(String filename) {
long size = new File(filename).length();
if (size != goodSize) {
System.out.println("File has wrong size!");
return;
}
try (BufferedReader br = new BufferedReader(new
Search WWH ::




Custom Search