I know that if I do something like
copyFromInToOut(new FileInputStream(f1), new FileOutputStream(f2));
System.gc();
It will run the GC on those FileInputStreams, closing them. But if I do
copyFromInToOut(new BufferedInputStream(new FileInputStream(f1)), new BufferedOutputStream(new FileOutputStream(f2));
System.gc();
Is there any danger that the FileOutputStream will be GCed before the BufferedOutputStream, not causing the buffer to flush?
I can’t call flush, close, because that takes more steps than this. It would first involve declaring a bufferedinputstream, passing, then calling close. OR am I safe to do this?
Don’t call
System.gc()explicitly. Don’t rely on finalizers to do anything. Especially if you don’t understand how garbage collection works. Explicit garbage collection requests can be ignored, and finalizers might never run.A well-written
copyFromInToOutmethod for streams is likely to use its own buffer internally, so wrapping the output should be unnecessary.Declare variables for the
FileInputStreamandFileOutputStream, and invokeclose()on each in afinallyblock: