HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Do I need to close my FileOutputStreams?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
closefileoutputstreamsneed

Problem

I have inlined temporary FileOutputStream that I am not able to explicitly close.

Is that a problem?

File raw = new File(uri.getPath());
Bitmap myBitmap = BitmapFactory.decodeFile(uri.getPath());

File compressedPicture = MEUtils.createTemporaryFile(getPackageName());
// see here
myBitmap.compress(Bitmap.CompressFormat.JPEG,
                  mObjectiveDefinitionForTakingPictureResult.getQuality(),
                  new FileOutputStream(compressedPicture));

JpegImageMetadata jpegMetadata = (JpegImageMetadata) Sanselan.getMetadata(raw);
TiffImageMetadata exif = jpegMetadata.getExif();
TiffOutputSet outputSet = exif.getOutputSet();
outputSet.setGPSInDegrees(app.locationListener.getLongitude(),
                          app.locationListener.getLatitude());

File compressedPictureWithMetadata = MEUtils.createTemporaryFile(getPackageName());
// see here
OutputStream compressedPictureWithMetadataOutputStream = new BufferedOutputStream(new FileOutputStream(compressedPictureWithMetadata));
new ExifRewriter().updateExifMetadataLossless(compressedPicture,
                                              compressedPictureWithMetadataOutputStream,
                                              outputSet);


EDIT

It seems that BufferedOutputStream can conveniently wrap a FileOutputStream, directly by inline it in the constructor: http://developer.android.com/reference/java/io/BufferedOutputStream.html

Solution

Yes, you do.

While the garbage collector does close your FileOutputStream (by calling finalize), it is not a good idea to rely on it because it runs unpredictably.

This means that if you do not close your streams explicitly, you may run into a limit on the number of simultaneously open files or into inability to open a file until you close the previous stream to it (on Windows) or into unpredictable file content if you open several streams to the same file (on Unix).

Context

StackExchange Code Review Q#33010, answer score: 5

Revisions (0)

No revisions yet.