Download a file from the remote server to a local directory.

@param remoteFile           Path and name of the remote file.
@param localTargetDirectory Local directory to put the downloaded file.
@throws IOException
432420
public void get(String remoteFile, String localTargetDirectory) throws IOException {
        get(new String[]{remoteFile}, localTargetDirectory);
    }
773832
public void downloadFileUsingRequesterPays(
      String projectId, String bucketName, String srcFilename, Path destFilePath)
      throws IOException {
    // [START storage_download_file_requester_pays]
    // The project ID to bill
    // String projectId = "my-billable-project-id";

    // The name of the bucket to access
    // String bucketName = "my-bucket";

    // The name of the remote file to download
    // String srcFilename = "file.txt";

    // The path to which the file should be downloaded
    // Path destFilePath = Paths.get("/local/path/to/file.txt");

    // Instantiate a Google Cloud Storage client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Get specific file from specified bucket
    Blob blob = storage.get(BlobId.of(bucketName, srcFilename));

    // Download file to specified path
    blob.downloadTo(destFilePath, Blob.BlobSourceOption.userProject(projectId));
    // [END storage_download_file_requester_pays]
  }
1364476
public Response download(String url, File destination) throws IOException {
		return download(url, destination, (String[]) null);
	}
581205
protected final void downloadFile(final URI source, final File destination) throws IOException {
        Validate.validState(!isStopped, "Cannot download file when the crawler is not started.");
        Validate.validState(!isStopping, "Cannot download file when the crawler is stopping.");
        Validate.notNull(source, "The source URL cannot be null.");
        Validate.notNull(destination, "The destination file cannot be null.");

        HttpGet request = new HttpGet(source);
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                FileUtils.copyInputStreamToFile(entity.getContent(), destination);
            }
        }
    }
972611
public static FtpMessage put(String localPath, String remotePath, DataType type) {
        PutCommand cmd = new PutCommand();
        cmd.setSignal(FTPCmd.STOR.getCommand());

        PutCommand.File file = new PutCommand.File();
        file.setPath(localPath);
        file.setType(type.name());
        cmd.setFile(file);

        PutCommand.Target target = new PutCommand.Target();
        target.setPath(remotePath);
        cmd.setTarget(target);
        return new FtpMessage(cmd);
    }
617195
public void downloadToLocalFile(IProgressMonitor monitor, File file)
      throws InvocationTargetException {

    final int taskSize = 1024;

    monitor.setTaskName("Download file " + this.path);

    BufferedOutputStream ostream = null;
    DataInputStream istream = null;

    try {
      istream = getDFS().open(this.path);
      ostream = new BufferedOutputStream(new FileOutputStream(file));

      int bytes;
      byte[] buffer = new byte[taskSize];

      while ((bytes = istream.read(buffer)) >= 0) {
        if (monitor.isCanceled())
          return;
        ostream.write(buffer, 0, bytes);
        monitor.worked(1);
      }

    } catch (Exception e) {
      throw new InvocationTargetException(e);

    } finally {
      // Clean all opened resources
      if (istream != null) {
        try {
          istream.close();
        } catch (IOException e) {
          e.printStackTrace();
          // nothing we can do here
        }
      }
      try {
        ostream.close();
      } catch (IOException e) {
        e.printStackTrace();
        // nothing we can do here
      }
    }
  }
643470
public String downloadFileFromServer(String url, String fileName, String targetFileDir) throws Exception {

        // 下载的路径
        String localDir = getLocalDownloadDirPath();

        // 设置远程地址
        RemoteUrl remoteUrl = new RemoteUrl(url, hostList);

        // 下载
        return restfulMgr
                .downloadFromServer(remoteUrl, fileName, localDir, localDownloadDirTemp, targetFileDir,
                        enableLocalDownloadDirInClassPath,
                        retryTime,
                        retrySleepSeconds);

    }
325888
private boolean download( URL target, File file )
    {

        _log.addDebug( "JarDiffHandler:  Doing download" );

        boolean ret = true;
        boolean delete = false;
        // use bufferedstream for better performance
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try
        {
            in = new BufferedInputStream( target.openStream() );
            out = new BufferedOutputStream( new FileOutputStream( file ) );
            int read = 0;
            int totalRead = 0;
            byte[] buf = new byte[BUF_SIZE];
            while ( ( read = in.read( buf ) ) != -1 )
            {
                out.write( buf, 0, read );
                totalRead += read;
            }

            _log.addDebug( "total read: " + totalRead );
            _log.addDebug( "Wrote URL " + target.toString() + " to file " + file );

        }
        catch ( IOException ioe )
        {

            _log.addDebug( "Got exception while downloading resource: " + ioe );

            ret = false;

            if ( file != null )
            {
                delete = true;
            }

        }
        finally
        {

            try
            {
                in.close();
                in = null;
            }
            catch ( IOException ioe )
            {
                _log.addDebug( "Got exception while downloading resource: " + ioe );
            }

            try
            {
                out.close();
                out = null;
            }
            catch ( IOException ioe )
            {
                _log.addDebug( "Got exception while downloading resource: " + ioe );
            }

            if ( delete )
            {
                file.delete();
            }

        }
        return ret;
    }
593658
public function download(String $remotePath, String $localPath) : Bool
    {
        if( @ssh2_scp_recv($this->connect, $remotePath, $localPath) )
        {
            return true;
        }
        else
        {
            throw new FileRemoteDownloadException(NULL, $localPath);
        }
    }
674543
public function wget($httpFile, $remote)
    {
        if (! ini_get('allow_url_fopen')) {
            throw new \RuntimeException('allow_url_fopen must enabled');
        }
        if (! $fileData = file_get_contents($httpFile)) {
            throw new \RuntimeException('Can nat get file content');
        }
        $parseFile = $this->parseLastDirectory($remote);
        if (! file_put_contents($this->getWrapper("/$parseFile"), $fileData)) {
            throw new FileException('File not uploaded to ftp server');
        }
        return true;
    }
1183475
public static void downloadResourcesAsSupervisorDirect(String key, String localFile,
                                                           ClientBlobStore cb) throws KeyNotFoundException, IOException {
        final int MAX_RETRY_ATTEMPTS = 2;
        final int ATTEMPTS_INTERVAL_TIME = 100;
        for (int retryAttempts = 0; retryAttempts < MAX_RETRY_ATTEMPTS; retryAttempts++) {
            if (downloadResourcesAsSupervisorAttempt(cb, key, localFile)) {
                break;
            }
            Utils.sleep(ATTEMPTS_INTERVAL_TIME);
        }
    }
107715
private function download(RemotePackageEntity $remotePackage)
    {
        $temp = $this->app->make(VolatileDirectory::class);
        /* @var VolatileDirectory $temp */
        $zipFilename = $temp->getPath() . '/downloaded.zip';
        $this->httpClient->reset();
        $this->httpClient->setOptions([
            'storeresponse' => false,
            'outputstream' => $zipFilename,
        ]);
        $request = new Request();

        if (($header = (string) getenv('CT_REMOTEPACKAGE_HEADER')) &&
            $value = (string) getenv('CT_REMOTEPACKAGE_HEADER_VALUE')) {
            $request->getHeaders()->addHeaderLine($header, $value);
        }
        $request->setMethod('GET')->setUri($remotePackage->getArchiveUrl());
        $response = $this->httpClient->send($request);
        $this->httpClient->reset();
        $streamHandle = ($response instanceof \Zend\Http\Response\Stream) ? $response->getStream() : null;
        if (is_resource($streamHandle)) {
            fclose($streamHandle);
        }
        if ($response->getStatusCode() != 200) {
            $error = t('Failed to download package archive %s v%s: %s (%d)', $remotePackage->getHandle(), $remotePackage->getVersion(), $response->getReasonPhrase(), $response->getStatusCode());
            unset($temp);
            throw new DownloadException($error, $response->getStatusCode());
        }

        $contentEncodingHeader = $response->getHeaders()->get('Content-Encoding');
        if (!empty($contentEncodingHeader)) {
            $contentEncoding = trim((string) $contentEncodingHeader->getFieldValue());
            if ($contentEncoding !== '') {
                $decodedZipFilename = $temp->getPath() . '/downloaded-decoded.zip';
                switch (strtolower($contentEncoding)) {
                    case 'gzip':
                        $this->decodeGzip($zipFilename, $decodedZipFilename);
                        break;
                    case 'deflate':
                        $this->decodeDeflate($zipFilename, $decodedZipFilename);
                        break;
                    case 'plainbinary':
                    default:
                        $decodedZipFilename = '';
                        break;
                }
                if ($decodedZipFilename !== '') {
                    $temp->getFilesystem()->delete([$zipFilename]);
                    $zipFilename = $decodedZipFilename;
                }
            }
        }

        $temp->getFilesystem()->makeDirectory($temp->getPath() . '/unzipped');
        $this->zip->unzip($zipFilename, $temp->getPath() . '/unzipped');
        $temp->getFilesystem()->delete([$zipFilename]);

        return $temp;
    }
724463
def download_file_powershell(url, target):
    
    target = os.path.abspath(target)
    cmd = [
        'powershell',
        '-Command',
        "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars(),
    ]
    _clean_check(cmd, target)
265377
def register_download_command(self, download_func):
        
        description = "Download the contents of a remote remote project to a local folder."
        download_parser = self.subparsers.add_parser('download', description=description)
        add_project_name_or_id_arg(download_parser, help_text_suffix="download")
        _add_folder_positional_arg(download_parser)
        include_or_exclude = download_parser.add_mutually_exclusive_group(required=False)
        _add_include_arg(include_or_exclude)
        _add_exclude_arg(include_or_exclude)
        download_parser.set_defaults(func=download_func)
1065690
public void copyTo(String localPath, String remotePath) throws Exception {
        FileInputStream fis = null;
        String rfile = remotePath;
        String localfile = localPath;
        boolean ptimestamp = true;

        // exec 'scp -t rfile' remotely
        String command = "scp " + (ptimestamp ? "-p" : "") + " -d -t " + rfile;
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);

        // get I/O streams for remote scp
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();

        channel.connect();

        if (checkAck(in) != 0) {
            return;
        }

        File myFile = new File(localfile);
        List<String> files = new ArrayList<String>();

        if (myFile.isDirectory()) {
            File[] listFiles = myFile.listFiles();
            for (File file : listFiles) {
                files.add(file.getAbsolutePath());
            }
        } else {
            files.add(localfile);
        }
        for (String lfile : files) {
            File _lfile = new File(lfile);

            if (ptimestamp) {
                command = "T" + (_lfile.lastModified() / 1000) + " 0";
                // The access time should be sent here,
                // but it is not accessible with JavaAPI ;-<
                command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
                out.write(command.getBytes());
                out.flush();
                if (checkAck(in) != 0) {
                    break;
                }
            }

            // send "C0644 filesize filename", where filename should not include '/'
            long filesize = _lfile.length();
            command = "C0644 " + filesize + " ";
            if (lfile.lastIndexOf('/') > 0) {
                command += lfile.substring(lfile.lastIndexOf('/') + 1);
            } else {
                command += lfile;
            }
            command += "\n";
            out.write(command.getBytes());
            out.flush();
            if (checkAck(in) != 0) {
                break;
            }

            // send a content of lfile
            fis = new FileInputStream(lfile);
            byte[] buf = new byte[1024];
            while (true) {
                int len = fis.read(buf, 0, buf.length);
                if (len <= 0) {
                    break;
                }
                out.write(buf, 0, len);
            }
            fis.close();
            fis = null;
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
            if (checkAck(in) != 0) {
                break;
            }
        }
        out.close();

        channel.disconnect();
    }
653104
private RemoteIterator<LocatedFileStatus> methodBasedListPathWithLocation(
      final String src) throws IOException {
    if (namenodeProtocolProxy.isMethodSupported(
        "getLocatedPartialListing", String.class, byte[].class)) {
      return iteratorListing(src);
    } else {
      return arrayListing(src);
    }
  }
1100736
def download_file(self, remote, local):
        
        file = open(local, 'wb')
        try:
            self.download(remote, file)
        finally:
            file.close()