Close stream on key export to avoid partial write (see #986)