Use more efficient indexing operations

http://findbugs.sourceforge.net/bugDescriptions.html#IIO_INEFFICIENT_INDEX_OF
Ensure that streams are closed