Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added try-with-resources

...

This compliant solution uses a directly allocated NIO (new I/O) buffer to read sensitive data from the file. The data can be cleared immediately after use and is not cached or buffered at multiple locations. It exists only in the system memory.

Code Block
bgColor#ccccff
private void readIntoDirectBuffer() throws IOException {
  ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
  try(FileChannel rdr = null;
  try {
    rdr = (new FileInputStream("file")).getChannel();
    ){
	while (rdr.read(buffer) > 0) {
      // Do something with the buffer
      	buffer.clear();
    	}
} 
catch }(Exception finallye) { 
    rdr.close(
	System.out.println("Exception creating file channel" + e);
}  }
}

Note that manual clearing of the buffer data is mandatory because direct buffers are exempt from garbage collection.

...