[FIX] Safely close the files

Change-Id: I0b3f7fcca3b79474fd3cc21257ccb6e82087590b