return a file object to write into the cache. The caller
        is responsibile for closing the stream. Bad things happen
        if you dont close the stream
345903
def put_stream(self, rel_path, metadata=None, cb=None):
        

        class flo:

            def __init__(self, this, sink, upstream, repo_path):
                self.this = this
                self.sink = sink
                self.upstream = upstream
                self.repo_path = repo_path

            @property
            def repo_path(self):
                return self.repo_path

            def write(self, d):
                self.sink.write(d)

                if self.upstream:
                    self.upstream.write(d)

            def writelines(self, lines):
                raise NotImplemented()

            def close(self):
                self.sink.close()

                size = os.path.getsize(self.repo_path)

                self.this.add_record(rel_path, size)
                self.this._free_up_space(size, this_rel_path=rel_path)

                if self.upstream:
                    self.upstream.close()
                    
            def __enter__(self): # Can be used as a context!
                return self

            def __exit__(self, type_, value, traceback):
                if type_:
                    return False

        if not isinstance(rel_path, basestring):
            rel_path = rel_path.cache_key

        repo_path = os.path.join(self.cache_dir, rel_path.strip('/'))

        if not os.path.isdir(os.path.dirname(repo_path)):
            os.makedirs(os.path.dirname(repo_path))

        self.put_metadata(rel_path, metadata=metadata)

        sink = open(repo_path, 'w+')
        upstream = self.upstream.put_stream(
            rel_path,
            metadata=metadata) if self.upstream else None

        return flo(self, sink, upstream, repo_path)
162269
def dump(self, stream=None):
        
        if stream is None:
            stream = BytesIO()

        if isinstance(stream, bytes):
            stream = BytesIO(stream)

        stream = self.codec.compress(stream)
        self.fs.dump(stream)

        return self
452992
def save_file(self):
        

        if not self.__is_untitled and foundations.common.path_exists(self.__file):
            return self.write_file(self.__file)
        else:
            return self.save_fileAs()
176922
private synchronized void writeObject(java.io.ObjectOutputStream stream)
			throws java.io.IOException
	{
		ThreadState tmp = this.threadState;
		this.threadStateSerilizationHashedId = serilizationCache.store(this.threadState);
		this.threadState = null;
		stream.defaultWriteObject();
		this.threadState = tmp;
	}
1056176
def save(self, destination: BinaryIO, buffer_size: int=16384) -> None:
        
        close_destination = False
        if isinstance(destination, str):
            destination = open(destination, 'wb')
            close_destination = True
        try:
            copyfileobj(self.stream, destination, buffer_size)
        finally:
            if close_destination:
                destination.close()
260146
def file_request(self):
        
        response = requests.get(
            self.__base_url,
            headers=self.__headers,
            stream=True)

        return response.raw.read(), response.headers
635830
def get_stream(data=None):
        
        if len(__mstreams_available__) == 0:
            if data:
                mstream = MemoryStream(data)
                mstream.seek(0)
            else:
                mstream = MemoryStream()
            __mstreams__.append(mstream)
            return mstream

        mstream = __mstreams_available__.pop()

        if data is not None and len(data):
            mstream.clean_up()
            mstream.write(data)

        mstream.seek(0)

        return mstream
910881
function WriteStream(path, options, flush) {
  // Not exposed so we can avoid the case where someone doesn't use `new`

  if (typeof options === 'function') {
    flush = options;
    options = null;
  }

  options = options || {};

  Writable.call(this, options);

  this.flush = flush;
  this.path = path;

  this.mode = options.mode || constants.DEFAULT_FILE_MODE;
  this.flags = options.flags || 'w';

  // Used by node's `fs.WriteStream`
  this.fd = null;
  this.start = null;

  this.open();

  // Dispose on finish.
  this.once('finish', this.close);
}
551090
public void closeFLACStream(byte[] md5Hash, StreamConfiguration streamConfig)
      throws IOException {
    //reset position in output stream to beginning.
    //re-write the updated stream info.
    streamLock.lock();
    try {
      if(!flacStreamIsOpen)
        throw new IllegalStateException("Error. Cannot close a non-opened stream");
      StreamConfiguration tempSC = new StreamConfiguration(streamConfig);
      tempSC.setMaxBlockSize(maxBlockSize);
      tempSC.setMinBlockSize(minBlockSize);
      EncodedElement streamInfo =  MetadataBlockStreamInfo.getStreamInfo(
          tempSC, minFrameSize, maxFrameSize, samplesInStream, md5Hash);
      if(out.canSeek()) {
        out.seek(streamHeaderPos);
        this.writeDataToOutput(streamInfo);
      }
      flacStreamIsOpen = false;
      out.close();
    } finally {
       streamLock.unlock();
    }
  }
384363
function writeStreamToFile(fileMeta, stream) {
  var deferred = q.defer();
  stream.on('end', function() {
    deferred.resolve(fileMeta);
  });
  stream.on('error', function(error) {
    deferred.reject(error);
  });
  var filename = imageDir + '/' + fileMeta.uid;
  stream.pipe(fs.createWriteStream(filename));
  return deferred.promise;
}
790477
private FileOutputStream fos() throws IOException {
        if (closed)
            throw new IOException("Output stream is already closed");
        if (os == null || currFileBytesWritten >= partSize) {
            if (os != null) {
                os.close();
                // notify about the new file ready for processing
                observer.onPartCreate(new PartCreationEvent(
                        getFile(filesCreated), filesCreated, false, this));
            }
            currFileBytesWritten = 0;
            filesCreated++;
            blockIfNecessary();
            final File file = getFile(filesCreated);
            os = new FileOutputStream(file);
        }
        return os;
    }
888345
File writeTempCacheFile(InputStream stream, FileExtension extension) throws IOException {
    String fileName = filenameForUrl(url, extension, true);
    File file = new File(appContext.getCacheDir(), fileName);
    try {
      OutputStream output = new FileOutputStream(file);
      //noinspection TryFinallyCanBeTryWithResources
      try {
        byte[] buffer = new byte[1024];
        int read;

        while ((read = stream.read(buffer)) != -1) {
          output.write(buffer, 0, read);
        }

        output.flush();
      } finally {
        output.close();
      }
    } finally {
      stream.close();
    }
    return file;
  }
761263
def download
      return io if io.is_a?(Tempfile)

      Tempfile.new(id, binmode: true).tap do |tempfile|
        IO.copy_stream(io, tempfile)
        tempfile.rewind
        tempfile.fsync
      end
    end
1136777
def to_file(self, outputfile=DEFAULT_OUTPUTFILE):
        
    
        if outputfile != NO_OUTPUTFILE:
            if outputfile == DEFAULT_OUTPUTFILE:
                outputfile = 'profile_' + str(hash(self)) + ".html"
            # TODO: should be done in the template
            with codecs.open(outputfile, 'w+b', encoding='utf8') as self.file:
                self.file.write(templates.template('wrapper').render(content=self.html))
1053239
public function stream_close()
    {
        @fclose($this->temporaryFileHandle);
        
        // Upload the file?
        if ($this->writeMode) {
            // Make sure the container exists
            if (! $this->containerExists($this->fileName)) {
                $this->getStorageClient($this->fileName)->createContainer($this->getContainerName($this->fileName));
            }
            
            $mimeTypeGuesser = MimeTypeGuesser::getInstance();
            $createBlobOptions = new CreateBlobOptions();
            $createBlobOptions->setBlobContentType($mimeTypeGuesser->guess($this->temporaryFileName));
            
            // Upload the file
            try {
                $result = $this->getStorageClient($this->fileName)->createBlockBlob($this->getContainerName($this->fileName), $this->getFileName($this->fileName), fopen($this->temporaryFileName, "r"), $createBlobOptions);
            } catch (Exception $ex) {
                $this->cleanup();
                
                throw $ex;
            }
        }
        
        $this->cleanup();
    }
296949
def write(self, byte):
        
        if self.is_closed_flag:
            raise Exception("Unable to write - already closed!")
        self.written += len(byte)
        self.file.write(byte)
1246745
function FileOutputStream(istream, destinationFilename, mode=false){
    // wrap into Promise
    return new Promise(function(resolve, reject){

        // file output stream
        let ostream = null;

        // on complete - chmod
        const onComplete = function(){
            // file mode defined ?
            if (mode){
                // set mode of destination file
                _fs.chmod(destinationFilename, mode, function(err){
                    if (err){
                        reject(err);
                    }else{
                        resolve();
                    }
                });
            }else{
                // finish
                resolve();
            }
        }

        // cleanup
        const onError = function(e){
            // detach finish listener!
            if (ostream){
                ostream.removeListener('finish', onComplete);
            }
            
            // close streams
            if (istream){
                istream.destroy();
            }
            if (ostream){
                ostream.end();
            }

            // throw error
            reject(e);
        }

        // add additional error listener to input stream
        istream.on('error', onError);

        // open write stream
        ostream = _fs.createWriteStream(destinationFilename);
        ostream.on('error', onError);
        ostream.on('finish', onComplete);

        // pipe in to out
        istream.pipe(ostream);
    });
}