org.apache.commons.io.FileUtils.copyURLToFile()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(11.5k)|赞(0)|评价(0)|浏览(1308)

本文整理了Java中org.apache.commons.io.FileUtils.copyURLToFile()方法的一些代码示例,展示了FileUtils.copyURLToFile()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。FileUtils.copyURLToFile()方法的具体详情如下:
包路径:org.apache.commons.io.FileUtils
类名称:FileUtils
方法名:copyURLToFile

FileUtils.copyURLToFile介绍

[英]Copies bytes from the URL source to a file destination. The directories up to destination will be created if they don't already exist. destination will be overwritten if it already exists.

Warning: this method does not set a connection or read timeout and thus might block forever. Use #copyURLToFile(URL,File,int,int)with reasonable timeouts to prevent this.
[中]将字节从URLsource复制到文件destination。如果目录不存在,则将创建高达destination的目录。destination如果已经存在,将被覆盖。
警告:此方法不会设置连接或读取超时,因此可能会永久阻塞。使用带有合理超时的#copyURLToFile(URL,File,int,int)来防止这种情况。

代码示例

代码示例来源:origin: rubenlagus/TelegramBots

private java.io.File downloadToTemporaryFile(String url, String tempFileName) throws IOException {
  java.io.File output = java.io.File.createTempFile(tempFileName, ".tmp");
  FileUtils.copyURLToFile(new URL(url), output);
  return output;
}

代码示例来源:origin: uber/okbuck

public static void copyResourceToProject(String resource, File destination) {
 try {
  FileUtils.copyURLToFile(FileUtil.class.getResource(resource), destination);
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: apache/geode

protected File copyResourceToDirectory(File directory, String fileName) throws IOException {
 URL url = getClass().getResource(fileName);
 File file = new File(directory, fileName);
 FileUtils.copyURLToFile(url, file);
 return file;
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Copies a single resource into the target folder, by the given name, and handle errors gracefully.
 */
private void copy(StaplerRequest req, StaplerResponse rsp, File dir, URL src, String name) throws ServletException, IOException {
  try {
    FileUtils.copyURLToFile(src,new File(dir, name));
  } catch (IOException e) {
    LOGGER.log(Level.SEVERE, "Failed to copy "+name,e);
    sendError("Failed to copy "+name+": "+e.getMessage(),req,rsp);
    throw new AbortException();
  }
}

代码示例来源:origin: gocd/gocd

void installActivatorJarToBundleDir(File pluginBundleExplodedDir) {
  URL activatorJar = findAndValidateActivatorJar();
  File pluginActivatorJarDestination = new File(new File(pluginBundleExplodedDir, GoPluginOSGiManifest.PLUGIN_DEPENDENCY_DIR), ACTIVATOR_JAR_NAME);
  try {
    FileUtils.copyURLToFile(activatorJar, pluginActivatorJarDestination);
  } catch (IOException e) {
    throw new RuntimeException(String.format("Failed to copy activator jar %s to bundle dependency dir: %s", activatorJar, pluginActivatorJarDestination), e);
  }
}

代码示例来源:origin: apache/geode

private static String createTemporaryCopy(String name, URL resource) {
  try {
   String filename = name.replaceFirst(".*/", "");
   File tmpFile = File.createTempFile(filename, null);
   tmpFile.deleteOnExit();
   FileUtils.copyURLToFile(resource, tmpFile);
   return tmpFile.getAbsolutePath();
  } catch (IOException e1) {
   throw new RuntimeException("Failed getting path to resource " + name, e1);
  }
 }
}

代码示例来源:origin: apache/incubator-pinot

private QuickstartTableRequest prepareRealtimeTableRequest()
  throws IOException {
 _realtimeQuickStartDataDir = new File("quickStartData" + System.currentTimeMillis());
 if (!_realtimeQuickStartDataDir.exists()) {
  Preconditions.checkState(_realtimeQuickStartDataDir.mkdirs());
 }
 File tableConfigFile = new File(_realtimeQuickStartDataDir, "airlineStats_realtime_table_config.json");
 URL resource = Quickstart.class.getClassLoader().getResource("sample_data/airlineStats_realtime_table_config.json");
 Preconditions.checkNotNull(resource);
 FileUtils.copyURLToFile(resource, tableConfigFile);
 return new QuickstartTableRequest("airlineStats", _schemaFile, tableConfigFile);
}

代码示例来源:origin: apache/incubator-gobblin

@Override
 public String retrieve(Config config, String targetDir) throws IOException {
  final String zipFile = appendSlash(targetDir) +
      StringUtils.substringAfterLast(this.uri, File.separator);
  LOGGER.debug("Downloading to zip: " + zipFile + " from uri: " + uri);
  FileUtils.copyURLToFile(new URL(this.uri), new File(zipFile));
  return zipFile;
 }
}

代码示例来源:origin: knightliao/disconf

/**
 * 进行下载
 */
@Override
public <T> T call() throws Exception {
  // 删除临时文件
  // LOGGER.info("start to remove tmp download file: " + ""
  // + localTmpFile.getAbsolutePath());
  if (localTmpFile.exists()) {
    localTmpFile.delete();
  }
  // start tp download
  LOGGER.debug("start to download. From: " + remoteUrl + " , TO: " + localTmpFile.getAbsolutePath());
  // 下载
  FileUtils.copyURLToFile(remoteUrl, localTmpFile);
  // check
  if (!OsUtil.isFileExist(localTmpFile.getAbsolutePath())) {
    throw new Exception("download is ok, but cannot find downloaded file." + localTmpFile);
  }
  // download success
  LOGGER.debug("download success!  " + localTmpFile.getAbsolutePath());
  return null;
}

代码示例来源:origin: deeplearning4j/dl4j-examples

public static void downloadAndUntar() throws IOException {
     File rootFile = new File(DATA_DIR);
     if (!rootFile.exists()) {
       rootFile.mkdir();
     }
     File tarFile = new File(DATA_DIR, "flower_photos.tgz");
     if (!tarFile.isFile()) {
       log.info("Downloading the flower dataset from "+DATA_URL+ "...");
       FileUtils.copyURLToFile(
           new URL(DATA_URL),
           tarFile);
     }
     ArchiveUtils.unzipFileTo(tarFile.getAbsolutePath(), rootFile.getAbsolutePath());
  }
}

代码示例来源:origin: deeplearning4j/dl4j-examples

public static void downloadAndUntar() throws IOException {
     File rootFile = new File(DATA_DIR);
     if (!rootFile.exists()) {
       rootFile.mkdir();
     }
     File tarFile = new File(DATA_DIR, "flower_photos.tgz");
     if (!tarFile.isFile()) {
       log.info("Downloading the flower dataset from "+DATA_URL+ "...");
       FileUtils.copyURLToFile(
           new URL(DATA_URL),
           tarFile);
     }
     ArchiveUtils.unzipFileTo(tarFile.getAbsolutePath(), rootFile.getAbsolutePath());
  }
}

代码示例来源:origin: apache/kylin

private void extractHTables(File dest) throws IOException {
  logger.info("These htables are going to be extracted:");
  for (String htable : htables) {
    logger.info(htable + "(required)");
  }
  File tableDir = new File(dest, "table");
  FileUtils.forceMkdir(tableDir);
  for (String htable : htables) {
    try {
      URL srcUrl = new URL(getHBaseMasterUrl() + "table.jsp?name=" + htable);
      File destFile = new File(tableDir, htable + ".html");
      FileUtils.copyURLToFile(srcUrl, destFile);
    } catch (Exception e) {
      logger.warn("HTable " + htable + "info fetch failed: ", e);
    }
  }
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Copies the bundled plugin from the given URL to the destination of the given file name (like 'abc.jpi'),
 * with a reasonable up-to-date check. A convenience method to be used by the {@link #loadBundledPlugins()}.
 */
protected void copyBundledPlugin(URL src, String fileName) throws IOException {
  LOGGER.log(FINE, "Copying {0}", src);
  fileName = fileName.replace(".hpi",".jpi"); // normalize fileNames to have the correct suffix
  String legacyName = fileName.replace(".jpi",".hpi");
  long lastModified = getModificationDate(src);
  File file = new File(rootDir, fileName);
  // normalization first, if the old file exists.
  rename(new File(rootDir,legacyName),file);
  // update file if:
  //  - no file exists today
  //  - bundled version and current version differs (by timestamp).
  if (!file.exists() || file.lastModified() != lastModified) {
    FileUtils.copyURLToFile(src, file);
    file.setLastModified(getModificationDate(src));
    // lastModified is set for two reasons:
    // - to avoid unpacking as much as possible, but still do it on both upgrade and downgrade
    // - to make sure the value is not changed after each restart, so we can avoid
    // unpacking the plugin itself in ClassicPluginStrategy.explode
  }
  // Plugin pinning has been deprecated.
  // See https://groups.google.com/d/msg/jenkinsci-dev/kRobm-cxFw8/6V66uhibAwAJ
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * If {@code jenkins.exe} is old compared to our copy,
 * schedule an overwrite (except that since it's currently running,
 * we can only do it when Jenkins restarts next time.)
 */
private void updateJenkinsExeIfNeeded() {
  try {
    File baseDir = getBaseDir();
    URL exe = getClass().getResource("/windows-service/jenkins.exe");
    String ourCopy = Util.getDigestOf(exe.openStream());
    for (String name : new String[]{"hudson.exe","jenkins.exe"}) {
      try {
        File currentCopy = new File(baseDir,name);
        if(!currentCopy.exists())   continue;
        String curCopy = new FilePath(currentCopy).digest();
        if(ourCopy.equals(curCopy))     continue; // identical
        File stage = new File(baseDir,name+".new");
        FileUtils.copyURLToFile(exe,stage);
        Kernel32.INSTANCE.MoveFileExA(stage.getAbsolutePath(),currentCopy.getAbsolutePath(),MOVEFILE_DELAY_UNTIL_REBOOT|MOVEFILE_REPLACE_EXISTING);
        LOGGER.info("Scheduled a replacement of "+name);
      } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Failed to replace "+name,e);
      } catch (InterruptedException e) {
      }
    }
  } catch (IOException e) {
    LOGGER.log(Level.SEVERE, "Failed to replace jenkins.exe",e);
  }
}

代码示例来源:origin: gocd/gocd

protected void copyPluginToThePluginDirectory(File pluginDir, String destinationFilenameOfPlugin) throws IOException, URISyntaxException {
  URL resource = getClass().getClassLoader().getResource("defaultFiles/descriptor-aware-test-plugin.jar");
  FileUtils.copyURLToFile(resource, new File(pluginDir, destinationFilenameOfPlugin));
}

代码示例来源:origin: gocd/gocd

private void copyPluginToThePluginDirectory(File pluginDir, String destinationFilenameOfPlugin) throws IOException, URISyntaxException {
  URL resource = getClass().getClassLoader().getResource("defaultFiles/" + destinationFilenameOfPlugin);
  FileUtils.copyURLToFile(resource, new File(pluginDir, destinationFilenameOfPlugin));
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testCopyURLToFileWithTimeout() throws Exception {
  // Creates file
  final File file = new File(getTestDirectory(), "testCopyURLToFileWithTimeout");
  file.deleteOnExit();
  // Loads resource
  final String resourceName = "/java/lang/Object.class";
  FileUtils.copyURLToFile(getClass().getResource(resourceName), file, 500, 500);
  // Tests that resuorce was copied correctly
  try (FileInputStream fis = new FileInputStream(file)) {
    assertTrue(
        "Content is not equal.",
        IOUtils.contentEquals(
            getClass().getResourceAsStream(resourceName),
            fis));
  }
  //TODO Maybe test copy to itself like for copyFile()
}

代码示例来源:origin: geoserver/geoserver

public static File unpackTestDataDir() throws Exception {
  URL url = AbstractSecurityServiceTest.class.getResource("/data_dir/default");
  if (!"file".equals(url.getProtocol())) {
    // means a dependency is using this directory via a jarfile, copy out manually
    File dataDir = File.createTempFile("data", "live", new File("./target"));
    dataDir.delete();
    dataDir.mkdirs();
    // TODO: instead of harcoding files, dynamically read all subentries from the jar
    // and copy them out
    FileUtils.copyURLToFile(
        AbstractSecurityServiceTest.class.getResource("/data_dir/default/dummy.txt"),
        new File(dataDir, "dummy.txt"));
    return dataDir;
  }
  return URLs.urlToFile(url);
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testCopyURLToFile() throws Exception {
  // Creates file
  final File file = new File(getTestDirectory(), getName());
  file.deleteOnExit();
  // Loads resource
  final String resourceName = "/java/lang/Object.class";
  FileUtils.copyURLToFile(getClass().getResource(resourceName), file);
  // Tests that resuorce was copied correctly
  try (FileInputStream fis = new FileInputStream(file)) {
    assertTrue(
        "Content is not equal.",
        IOUtils.contentEquals(
            getClass().getResourceAsStream(resourceName),
            fis));
  }
  //TODO Maybe test copy to itself like for copyFile()
}

代码示例来源:origin: SonarSource/sonarqube

@Before
public void prepare() throws IOException {
 MockitoAnnotations.initMocks(this);
 File baseDir = temp.newFolder();
 context = SensorContextTester.create(baseDir);
 file = new TestInputFileBuilder("foo", "src/ManyStatements.java")
  .setModuleBaseDir(baseDir.toPath())
  .setCharset(StandardCharsets.UTF_8)
  .setLanguage("java").build();
 context.fileSystem().add(file);
 File ioFile = file.file();
 FileUtils.copyURLToFile(this.getClass().getResource("ManyStatements.java"), ioFile);
}

相关文章

微信公众号

最新文章

更多

FileUtils类方法