A server-side method to respond to a getfile http request
Copies the contents of the local file into the output stream,
starting at the given position, sending lengthToSend bytes.
553963
public static void getFileServerForPartialFiles(OutputStream outstream,
      String filename, InputStream infile, DataTransferThrottler throttler,
      long startPosition, long lengthToSend) throws IOException {
    byte buf[] = new byte[BUFFER_SIZE];
    try {
      int num = 1;
      while (num > 0) {
        num = infile.read(buf, 0,
            Math.min(BUFFER_SIZE,
                (int) Math.min(lengthToSend, Integer.MAX_VALUE)));
        lengthToSend -= num;
        if (num <= 0) {
          break;
        }
        try {
          outstream.write(buf, 0, num);
        } catch (Exception e) {
          // silently ignore. connection might have been closed
          break;
        }
        if (throttler != null) {
          throttler.throttle(num);
        }
      }
      if (lengthToSend > 0) {
        LOG.warn("Could not serve requested number of bytes. Left with "
            + lengthToSend + " bytes for file: " + filename);
      }
    } finally {
      if (infile != null) {
        infile.close();
      }
    }
  }
1014085
function copyFile(source, target, copyCallback) {
    const readStream = fs.createReadStream(source);
    const writeStream = fs.createWriteStream(target);
    let done = false;

    readStream.on('error', copyDone);
    writeStream.on('error', copyDone);

    writeStream.on('close', function onWriteCb() {
        copyDone(null);
    });

    readStream.pipe(writeStream);

    /**
     * Finish copying. Reports error when needed
     * @param [error] optional error
     */
    function copyDone(error) {
        if (!done) {
            done = true;
            copyCallback(error);
        }
    }
}
189324
protected long readFromFile(OutputStream stream, File file, long length, long position) throws IOException
   {
      FileInputStream in = null;

      try
      {
         if (channel == null || !channel.isOpen())
         {
            in = PrivilegedFileHelper.fileInputStream(file);
            channel = in.getChannel();
         }

         length = validateAndAdjustLenght(length, position, channel.size());

         MappedByteBuffer bb = channel.map(FileChannel.MapMode.READ_ONLY, position, length);

         WritableByteChannel ch = Channels.newChannel(stream);
         ch.write(bb);
         ch.close();

         return length;
      }
      finally
      {
         if (in != null)
         {
            in.close();
            if (channel != null)
            {
               channel.close();
            }
         }
      }
   }
480135
public static String getFileContent(InputStream inputStream, long offset, int length)
            throws Exception {
        byte[] fileContent = getFileContentByte(inputStream, offset, length);
        return new String(fileContent, Charset.forName("ISO-8859-1"));
    }
1217947
public static void downloadDataToSink( CResponse response, ByteSink byteSink )
    {
        InputStream is = null;
        ByteSinkStream bss = null;
        boolean success = false;
        try {

            long contentLength = response.getContentLength();
            if ( contentLength >= 0 ) {
                // content length is known: inform any listener
                byteSink.setExpectedLength( contentLength );
            }

            long current = 0;
            is = response.openStream();
            bss = byteSink.openStream();

            byte[] buffer = new byte[ 8 * 1024 ];
            int len;
            while ( ( len = is.read( buffer ) ) != -1 ) {
                current += len;
                bss.write( buffer, 0, len );
            }

            if ( contentLength < 0 ) {
                // content length was unknown; inform listener operation is terminated
                byteSink.setExpectedLength( current );
            }

            bss.flush();
            bss.close();
            bss = null;

            success = true;

        } catch ( IOException ex ) {
            throw new CStorageException( ex.getMessage(), ex );
        } finally {
            if ( bss != null && !success ) {
                bss.abort();
            }

            PcsUtils.closeQuietly( is );
            PcsUtils.closeQuietly( bss );
        }
    }
1072674
function(inputFile, outputFile, content) {
                return Promise()
                .then(function() {
                    var outputFilePath = PathUtils.resolveInRoot(outputFolder, outputFile);

                    return fs.ensureFile(outputFilePath)
                    .then(function() {
                        return fs.copy(inputFile, outputFilePath);
                    });
                });
            }
89402
def stream_copy(source, destination, chunk_size=512 * 1024):
    """"""
    br = 0
    while True:
        chunk = source.read(chunk_size)
        destination.write(chunk)
        br += len(chunk)
        if len(chunk) < chunk_size:
            break
    # END reading output stream
    return br
172869
public void getBytes(int lengthToCopy, byte[] copyArray, int copyOffset) {
        if (lengthToCopy > 0) {
            System.arraycopy(_buffer, _offset, copyArray, copyOffset, lengthToCopy);
            skip(lengthToCopy);
        }

    }
1266460
private AFTPClient actionGetFile() throws PageException, IOException {
	required("remotefile", remotefile);
	required("localfile", localfile);

	AFTPClient client = getClient();
	Resource local = ResourceUtil.toResourceExistingParent(pageContext, localfile);// new File(localfile);
	pageContext.getConfig().getSecurityManager().checkFileLocation(local);
	if (failifexists && local.exists()) throw new ApplicationException("File [" + local + "] already exist, if you want to overwrite, set attribute failIfExists to false");
	OutputStream fos = null;
	client.setFileType(getType(local));
	boolean success = false;
	try {
	    fos = IOUtil.toBufferedOutputStream(local.getOutputStream());
	    success = client.retrieveFile(remotefile, fos);
	}
	finally {
	    IOUtil.closeEL(fos);
	    if (!success) local.delete();
	}
	writeCfftp(client);

	return client;
    }
878242
def _process_response(self, resp, out_folder=None):
        
        CHUNK = 4056
        maintype = self._mainType(resp)
        contentDisposition = resp.headers.get('content-disposition')
        contentEncoding = resp.headers.get('content-encoding')
        contentType = resp.headers.get('content-type')
        contentLength = resp.headers.get('content-length')
        if maintype.lower() in ('image',
                                'application/x-zip-compressed') or \
           contentType == 'application/x-zip-compressed' or \
           (contentDisposition is not None and \
            contentDisposition.lower().find('attachment;') > -1):
            fname = self._get_file_name(
                contentDisposition=contentDisposition,
                url=resp.geturl())
            if out_folder is None:
                out_folder = tempfile.gettempdir()
            if contentLength is not None:
                max_length = int(contentLength)
                if max_length < CHUNK:
                    CHUNK = max_length
            file_name = os.path.join(out_folder, fname)
            with open(file_name, 'wb') as writer:
                for data in self._chunk(response=resp):
                    writer.write(data)
                    del data
                del writer
            return file_name
        else:
            read = ""
            for data in self._chunk(response=resp, size=4096):
                if self.PY3 == True:
                    read += data.decode('utf-8')
                else:
                    read += data
                del data
            try:
                return json.loads(read.strip())
            except:
                return read
        return None
533745
private void copyStream(InputStream inputStream) throws IOException {
		OutputStream outputStream = null;
		try {
			outputStream = getContext().getOutputStream();
			byte[] buffer = new byte[65535];
			int bufferLen;
			int totalLen = 0;
			while ((bufferLen = inputStream.read(buffer)) > 0) {
				outputStream.write(buffer, 0, bufferLen);
				totalLen += bufferLen;
			}
			getContext().getResponse().setContentLength(totalLen);
		} finally {
			if (outputStream != null) {
				outputStream.flush();
			}
		}
	}
101503
function handleTernGetFile(request) {

            function replyWith(name, txt) {
                _postMessageByPass({
                    type: MessageIds.TERN_GET_FILE_MSG,
                    file: name,
                    text: txt
                });
            }

            var name = request.file;

            /**
             * Helper function to get the text of a given document and send it to tern.
             * If DocumentManager successfully gets the file's text then we'll send it to the tern node domain.
             * The Promise for getDocumentText() is returned so that custom fail functions can be used.
             *
             * @param {string} filePath - the path of the file to get the text of
             * @return {jQuery.Promise} - the Promise returned from DocumentMangaer.getDocumentText()
             */
            function getDocText(filePath) {
                if (!FileSystem.isAbsolutePath(filePath) || // don't handle URLs
                        filePath.slice(0, 2) === "//") { // don't handle protocol-relative URLs like //example.com/main.js (see #10566)
                    return (new $.Deferred()).reject().promise();
                }

                var file = FileSystem.getFileForPath(filePath),
                    promise = DocumentManager.getDocumentText(file);

                promise.done(function (docText) {
                    resolvedFiles[name] = filePath;
                    numResolvedFiles++;
                    replyWith(name, filterText(docText));
                });
                return promise;
            }

            /**
             * Helper function to find any files in the project that end with the
             * name we are looking for.  This is so we can find requirejs modules
             * when the baseUrl is unknown, or when the project root is not the same
             * as the script root (e.g. if you open the 'brackets' dir instead of 'brackets/src' dir).
             */
            function findNameInProject() {
                // check for any files in project that end with the right path.
                var fileName = name.substring(name.lastIndexOf("/") + 1);

                function _fileFilter(entry) {
                    return entry.name === fileName;
                }

                ProjectManager.getAllFiles(_fileFilter).done(function (files) {
                    var file;
                    files = files.filter(function (file) {
                        var pos = file.fullPath.length - name.length;
                        return pos === file.fullPath.lastIndexOf(name);
                    });

                    if (files.length === 1) {
                        file = files[0];
                    }
                    if (file) {
                        getDocText(file.fullPath).fail(function () {
                            replyWith(name, "");
                        });
                    } else {
                        replyWith(name, "");
                    }
                });
            }

            if (!isFileExcludedInternal(name)) {
                getDocText(name).fail(function () {
                    getDocText(rootTernDir + name).fail(function () {
                        // check relative to project root
                        getDocText(projectRoot + name)
                            // last look for any files that end with the right path
                            // in the project
                            .fail(findNameInProject);
                    });
                });
            }
        }
172883
private void copy(final InputStream inputStream, final FileOutputStream outputStream) throws IOException {
        final byte[] buffer = new byte[1024*4];
        int n;
        try {
            while (-1 != (n = inputStream.read(buffer))) {
                outputStream.write(buffer, 0, n);
            }
        } finally {
            inputStream.close();
            outputStream.close();
        }
    }
624853
private InputStream getCopyOfResponseContent(InputStream is) throws FMSException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		InputStream copyIs = null; 
		try {
			byte[] bbuf = new byte[LENGTH_256];
			while (true) {
				int r = is.read(bbuf);
				if (r < 0) {
					break;
				}
				baos.write(bbuf, 0, r);
			}
			copyIs = new ByteArrayInputStream(baos.toByteArray());			
			return copyIs;
		} catch (IOException ioe) {
			LOG.error("IOException while decompress the data using GZIP compression.", ioe);
			throw new CompressionException(ioe);
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					LOG.error("Unable to close ByteArrayOutputStream.");
				}
			}
		}
	}
1258617
public static long copyUrl(OutputStream dst, URL src) throws IOException {
		long copied;

		try (InputStream srcStream = src.openStream()) {
			copied = copyStream(dst, srcStream);
		}
		return copied;
	}
735642
public static long copy(
                    final InputStream input,
                    final File output
                    )
    throws IOException
    {
        OutputStream  stream_output = null;
        long  size = 0L;
        try {
            stream_output = new FileOutputStream( output );
                            //throws FileNotFoundException
            size = copy( input, stream_output );
                   //throws IOException
        } finally {
            try {
                stream_output.close();
            } catch (Exception ex) {
                //ignorable
            }
        }

        return size;

    }
235624
public void copyToOutputStream(OutputStream o) throws IOException {
		long left = end - start;
		int BUFF_SIZE = 4096;
		byte buf[] = new byte[BUFF_SIZE];
		RandomAccessFile raf = new RandomAccessFile(file, "r");
		try {
			raf.seek(start);
			while(left > 0) {
				int amtToRead = (int) Math.min(left, BUFF_SIZE);
				int amtRead = raf.read(buf, 0, amtToRead);
				if(amtRead < 0) {
					throw new IOException("Not enough to read! EOF before expected region end");
				}
				o.write(buf,0,amtRead);
				left -= amtRead;
			}
		} finally {
			raf.close();
		}
	}