Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2008 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.io;
 
 
 import java.io.File;
An java.io.OutputStream that starts buffering to a byte array, but switches to file buffering once the data reaches a configurable size.

This class is thread-safe.

Author(s):
Chris Nokleberg
Since:
1.0
 
 public final class FileBackedOutputStream extends OutputStream {
 
   private final int fileThreshold;
   private final boolean resetOnFinalize;
   private final ByteSource source;
 
   private OutputStream out;
   private MemoryOutput memory;
   private File file;

  
ByteArrayOutputStream that exposes its internals.
 
   private static class MemoryOutput extends ByteArrayOutputStream {
     byte[] getBuffer() {
       return ;
     }
 
     int getCount() {
       return ;
     }
   }

  
Returns the file holding the data (possibly null).
 
   @VisibleForTesting synchronized File getFile() {
     return ;
   }

  
Creates a new instance that uses the given file threshold, and does not reset the data when the ByteSource returned by asByteSource() is finalized.

Parameters:
fileThreshold the number of bytes before the stream should switch to buffering to a file
 
   public FileBackedOutputStream(int fileThreshold) {
     this(fileThresholdfalse);
   }

  
Creates a new instance that uses the given file threshold, and optionally resets the data when the ByteSource returned by asByteSource() is finalized.

Parameters:
fileThreshold the number of bytes before the stream should switch to buffering to a file
resetOnFinalize if true, the reset() method will be called when the ByteSource returned by asByteSource() is finalized
 
   public FileBackedOutputStream(int fileThresholdboolean resetOnFinalize) {
     this. = fileThreshold;
     this. = resetOnFinalize;
      = new MemoryOutput();
      = ;
 
     if (resetOnFinalize) {
        = new ByteSource() {
         @Override
         public InputStream openStream() throws IOException {
          return openInputStream();
        }
        @Override protected void finalize() {
          try {
            reset();
          } catch (Throwable t) {
            t.printStackTrace(.);
          }
        }
      };
    } else {
       = new ByteSource() {
        @Override
        public InputStream openStream() throws IOException {
          return openInputStream();
        }
      };
    }
  }

  
Returns a readable ByteSource view of the data that has been written to this stream.

Since:
15.0
  public ByteSource asByteSource() {
    return ;
  }
  private synchronized InputStream openInputStream() throws IOException {
    if ( != null) {
      return new FileInputStream();
    } else {
      return new ByteArrayInputStream(
          .getBuffer(), 0, .getCount());
    }
  }

  
Calls close() if not already closed, and then resets this object back to its initial state, for reuse. If data was buffered to a file, it will be deleted.

Throws:
java.io.IOException if an I/O error occurred while deleting the file buffer
  public synchronized void reset() throws IOException {
    try {
      close();
    } finally {
      if ( == null) {
         = new MemoryOutput();
      } else {
        .reset();
      }
       = ;
      if ( != null) {
        File deleteMe = ;
         = null;
        if (!deleteMe.delete()) {
          throw new IOException("Could not delete: " + deleteMe);
        }
      }
    }
  }
  @Override public synchronized void write(int bthrows IOException {
    update(1);
    .write(b);
  }
  @Override public synchronized void write(byte[] bthrows IOException {
    write(b, 0, b.length);
  }
  @Override public synchronized void write(byte[] bint offint len)
      throws IOException {
    update(len);
    .write(bofflen);
  }
  @Override public synchronized void close() throws IOException {
    .close();
  }
  @Override public synchronized void flush() throws IOException {
    .flush();
  }

  
Checks if writing len bytes would go over threshold, and switches to file buffering if so.
  private void update(int lenthrows IOException {
    if ( == null && (.getCount() + len > )) {
      File temp = File.createTempFile("FileBackedOutputStream"null);
      if () {
        // Finalizers are not guaranteed to be called on system shutdown;
        // this is insurance.
        temp.deleteOnExit();
      }
      FileOutputStream transfer = new FileOutputStream(temp);
      transfer.write(.getBuffer(), 0, .getCount());
      transfer.flush();
      // We've successfully transferred the data; switch to writing to file
       = transfer;
       = temp;
       = null;
    }
  }
New to GrepCode? Check out our FAQ X