Class FileBackedOutputStream

java.lang.Object
java.io.OutputStream
com.google.common.io.FileBackedOutputStream
All Implemented Interfaces:
Closeable, Flushable, AutoCloseable

@Beta @GwtIncompatible @J2ObjCIncompatible public final class FileBackedOutputStream extends OutputStream
An OutputStream that starts buffering to a byte array, but switches to file buffering once the data reaches a configurable size.

When this stream creates a temporary file, it restricts the file's permissions to the current user or, in the case of Android, the current app. If that is not possible (as is the case under the very old Android Ice Cream Sandwich release), then this stream throws an exception instead of creating a file that would be more accessible. (This behavior is new in Guava 32.0.0. Previous versions would create a file that is more accessible, as discussed in CVE-2023-2976.

Temporary files created by this stream may live in the local filesystem until either:

  • reset() is called (removing the data in this stream and deleting the file), or...
  • this stream (or, more precisely, its asByteSource() view) is garbage collected, AND this stream was constructed with the two-arg constructor with true for the second parameter. Relying on this second approach is discouraged.

This class is thread-safe.

Since:
1.0
Author:
Chris Nokleberg
  • Constructor Details

    • FileBackedOutputStream

      public FileBackedOutputStream(int fileThreshold)
      Creates a new instance that uses the given file threshold, and does not reset the data when the ByteSource returned by asByteSource() is garbage collected.
      Parameters:
      fileThreshold - the number of bytes before the stream should switch to buffering to a file
      Throws:
      IllegalArgumentException - if fileThreshold is negative
    • FileBackedOutputStream

      public FileBackedOutputStream(int fileThreshold, boolean resetWhenGarbageCollected)
      Creates a new instance that uses the given file threshold, and optionally resets the data when the ByteSource returned by asByteSource() is garbage collected. Prefer to reset() the stream explicitly, rather than rely on garbage collection: If you call reset() explicitly, you can call it more promptly, and you can appropriately handle any exception that results.
      Parameters:
      fileThreshold - the number of bytes before the stream should switch to buffering to a file
      resetWhenGarbageCollected - if true, the reset() method will be called when the ByteSource returned by asByteSource() is garbage collected.
      Throws:
      IllegalArgumentException - if fileThreshold is negative
  • Method Details