Generics5

Mostly migrating existing code from raw to proper generic types. 
Also closing some streams that might fail to be closed in case of exception.
And using enhanced for loop to make the code more readable and removing some unnecessary null checks, redundant imports etc (see comments).