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

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

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

FileUtils.copyFileToDirectory介绍

[英]Copies a file to a directory preserving the file date.

This method copies the contents of the specified source file to a file of the same name in the specified destination directory. The destination directory is created if it does not exist. If the destination file exists, then this method will overwrite it.

Note: This method tries to preserve the file's last modified date/times using File#setLastModified(long), however it is not guaranteed that the operation will succeed. If the modification operation fails, no indication is provided.
[中]将文件复制到保留文件日期的目录。
此方法将指定源文件的内容复制到指定目标目录中同名的文件中。如果目标目录不存在,则创建该目录。如果目标文件存在,则此方法将覆盖它。
注意:此方法尝试使用file#setlastmedited(long)保留文件的上次修改日期/时间,但不能保证操作会成功。如果修改操作失败,则不提供任何指示。

代码示例

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

/**
 * Copies a file to a directory preserving the file date.
 * <p>
 * This method copies the contents of the specified source file
 * to a file of the same name in the specified destination directory.
 * The destination directory is created if it does not exist.
 * If the destination file exists, then this method will overwrite it.
 * <p>
 * <strong>Note:</strong> This method tries to preserve the file's last
 * modified date/times using {@link File#setLastModified(long)}, however
 * it is not guaranteed that the operation will succeed.
 * If the modification operation fails, no indication is provided.
 *
 * @param srcFile an existing file to copy, must not be {@code null}
 * @param destDir the directory to place the copy in, must not be {@code null}
 *
 * @throws NullPointerException if source or destination is null
 * @throws IOException          if source or destination is invalid
 * @throws IOException          if an IO error occurs during copying
 * @see #copyFile(File, File, boolean)
 */
public static void copyFileToDirectory(final File srcFile, final File destDir) throws IOException {
  copyFileToDirectory(srcFile, destDir, true);
}

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

/**
 * Copies a file to a directory preserving the file date.
 * <p>
 * This method copies the contents of the specified source file
 * to a file of the same name in the specified destination directory.
 * The destination directory is created if it does not exist.
 * If the destination file exists, then this method will overwrite it.
 *
 * @param srcFile  an existing file to copy, must not be <code>null</code>
 * @param destDir  the directory to place the copy in, must not be <code>null</code>
 *
 * @throws NullPointerException if source or destination is null
 * @throws IOException if source or destination is invalid
 * @throws IOException if an IO error occurs during copying
 * @see #copyFile(File, File, boolean)
 */
public static void copyFileToDirectory(File srcFile, File destDir) throws IOException {
  copyFileToDirectory(srcFile, destDir, true);
}

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

/**
 * Copies a files to a directory preserving each file's date.
 * <p>
 * This method copies the contents of the specified source files
 * to a file of the same name in the specified destination directory.
 * The destination directory is created if it does not exist.
 * If the destination file exists, then this method will overwrite it.
 * <p>
 * <strong>Note:</strong> This method tries to preserve the file's last
 * modified date/times using {@link File#setLastModified(long)}, however
 * it is not guaranteed that the operation will succeed.
 * If the modification operation fails, no indication is provided.
 *
 * @param srcs     a existing files to copy, must not be {@code null}
 * @param destDir  the directory to place the copy in, must not be {@code null}
 *
 * @throws NullPointerException if source or destination is null
 * @throws IOException if source or destination is invalid
 * @throws IOException if an IO error occurs during copying
 * @see #copyFileToDirectory(File, File)
 * @since 2.6
 */
public static void copyToDirectory(final Iterable<File> srcs, final File destDir) throws IOException {
  if (srcs == null) {
    throw new NullPointerException("Sources must not be null");
  }
  for (final File src : srcs) {
    copyFileToDirectory(src, destDir);
  }
}

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

copyFileToDirectory(src, destDir);
} else if (src.isDirectory()) {
  copyDirectoryToDirectory(src, destDir);

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

@Override
  public void run() {
    logger.info("Start to extract kylin conf files.");
    try {
      File destConfDir = new File(exportDir, "conf");
      FileUtils.forceMkdir(destConfDir);
      File srcConfDir = new File(ToolUtil.getConfFolder());
      Preconditions.checkState(srcConfDir.exists(),
          "Cannot find config dir: " + srcConfDir.getAbsolutePath());
      File[] confFiles = srcConfDir.listFiles();
      if (confFiles != null) {
        for (File confFile : confFiles) {
          FileUtils.copyFileToDirectory(confFile, destConfDir);
        }
      }
    } catch (Exception e) {
      logger.error("Error in export conf.", e);
    }
  }
});

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

private void copyOplogFile(DiskStore diskStore, DirectoryHolder dirHolder, File file)
  throws IOException {
 if (file == null || !file.exists()) {
  return;
 }
 Path tempDiskDir = temporaryFiles.getDiskStoreDirectory(diskStore, dirHolder);
 try {
  createLink(tempDiskDir.resolve(file.getName()), file.toPath());
 } catch (IOException e) {
  logger.warn("Unable to create hard link for {}. Reverting to file copy",
    tempDiskDir.toString());
  FileUtils.copyFileToDirectory(file, tempDiskDir.toFile());
 }
 backupDefinition.addOplogFileToBackup(diskStore, tempDiskDir.resolve(file.getName()));
}

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

private void dumpBasicDiagInfo() throws IOException {
  try {
    for (String commitSHA1File : COMMIT_SHA1_FILES) {
      File commitFile = new File(KylinConfig.getKylinHome(), commitSHA1File);
      if (commitFile.exists()) {
        FileUtils.copyFileToDirectory(commitFile, exportDir);
      }
    }
  } catch (IOException e) {
    logger.warn("Failed to copy commit_SHA1 file.", e);
  }
  String output = KylinVersion.getKylinClientInformation() + "\n";
  FileUtils.writeStringToFile(new File(exportDir, "kylin_env"), output, Charset.defaultCharset());
  StringBuilder basicSb = new StringBuilder();
  basicSb.append("MetaStoreID: ").append(ToolUtil.getMetaStoreId()).append("\n");
  basicSb.append("PackageType: ").append(packageType.toUpperCase(Locale.ROOT)).append("\n");
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ROOT);
  basicSb.append("PackageTimestamp: ").append(format.format(new Date())).append("\n");
  basicSb.append("Host: ").append(ToolUtil.getHostName()).append("\n");
  FileUtils.writeStringToFile(new File(exportDir, "info"), basicSb.toString(), Charset.defaultCharset());
}

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

/**
 * Copy file to styles directory (determined using {@link StyleInfo#getWorkspace()}).
 *
 * @param file
 * @param style
 * @throws IOException
 * @deprecated As of GeoServer 2.6, replaced by {@link #get(StyleInfo, String...)}
 */
@Deprecated
public void copyToStyleDir(File file, StyleInfo style) throws IOException {
  Resource styles = get(style);
  FileUtils.copyFileToDirectory(file, styles.dir());
}

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

public void copyTo(File targetDir) throws IOException {
 lock(false);
 try {
  FileUtils.copyFileToDirectory(this.ifFile, targetDir);
 } finally {
  unlock(false);
 }
}

代码示例来源:origin: internetarchive/heritrix3

public void snapshotToLaunchDir(File readFile) throws IOException {
  if(appCtx.getCurrentLaunchDir()==null|| !appCtx.getCurrentLaunchDir().exists()) {
    logger.log(Level.WARNING, "launch directory unavailable to snapshot "+readFile); 
    return; 
  }
  FileUtils.copyFileToDirectory(readFile, appCtx.getCurrentLaunchDir());
}

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

private void downloadRelease(Release release) throws URISyntaxException, IOException {
 String url = release.getDownloadUrl();
 URI uri = new URI(url);
 if (url.startsWith("file:")) {
  // used for tests
  File file = toFile(uri.toURL());
  copyFileToDirectory(file, downloadDir);
 } else {
  String filename = substringAfterLast(uri.getPath(), "/");
  if (!filename.endsWith("." + PLUGIN_EXTENSION)) {
   filename = release.getKey() + "-" + release.getVersion() + "." + PLUGIN_EXTENSION;
  }
  File targetFile = new File(downloadDir, filename);
  File tempFile = new File(downloadDir, filename + "." + TMP_SUFFIX);
  downloader.download(uri, tempFile);
  copyFile(tempFile, targetFile);
  deleteQuietly(tempFile);
 }
}

代码示例来源:origin: internetarchive/heritrix3

protected void initLaunchDir() {
  initLaunchId();
  try {
    currentLaunchDir = new File(getConfigurationFile().getParentFile(), getCurrentLaunchId());
    if (!currentLaunchDir.mkdir()) {
      throw new IOException("failed to create directory " + currentLaunchDir);
    }
    
    // copy cxml to launch dir
    FileUtils.copyFileToDirectory(getConfigurationFile(), currentLaunchDir);
    
    // attempt to symlink "latest" to launch dir
    File latestSymlink = new File(getConfigurationFile().getParentFile(), "latest");
    latestSymlink.delete();
    boolean success = FilesystemLinkMaker.makeSymbolicLink(currentLaunchDir.getName(), latestSymlink.getPath());
    if (!success) {
      LOGGER.warning("failed to create symlink from " + latestSymlink + " to " + currentLaunchDir);
    }
  } catch (IOException e) {
    LOGGER.log(Level.SEVERE, "failed to initialize launch directory: " + e);
    currentLaunchDir = null;
  }
}

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

private File copyTestPluginTo(String testPluginName, File toDir) throws IOException {
  File jar = TestProjectUtils.jarOf(testPluginName);
  // file is copied because it's supposed to be moved by the test
  FileUtils.copyFileToDirectory(jar, toDir);
  return new File(toDir, jar.getName());
 }
}

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

private File copyTestPluginTo(String testPluginName, File toDir) throws IOException {
  File jar = TestProjectUtils.jarOf(testPluginName);
  // file is copied because it's supposed to be moved by the test
  FileUtils.copyFileToDirectory(jar, toDir);
  return new File(toDir, jar.getName());
 }
}

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

@Test
public void testCopyFile2ToDir() throws Exception {
  final File directory = new File(getTestDirectory(), "subdir");
  if (!directory.exists()) {
    directory.mkdirs();
  }
  final File destination = new File(directory, testFile1.getName());
  //Thread.sleep(LAST_MODIFIED_DELAY);
  //This is to slow things down so we can catch if
  //the lastModified date is not ok
  FileUtils.copyFileToDirectory(testFile1, directory);
  assertTrue("Check Exist", destination.exists());
  assertEquals("Check Full copy", testFile2Size, destination.length());
  /* disabled: Thread.sleep doesn't work reliantly for this case
  assertTrue("Check last modified date preserved",
    testFile1.lastModified() == destination.lastModified());*/
}

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

@Test
public void testCopyFile1ToDir() throws Exception {
  final File directory = new File(getTestDirectory(), "subdir");
  if (!directory.exists()) {
    directory.mkdirs();
  }
  final File destination = new File(directory, testFile1.getName());
  //Thread.sleep(LAST_MODIFIED_DELAY);
  //This is to slow things down so we can catch if
  //the lastModified date is not ok
  FileUtils.copyFileToDirectory(testFile1, directory);
  assertTrue("Check Exist", destination.exists());
  assertEquals("Check Full copy", testFile1Size, destination.length());
  /* disabled: Thread.sleep doesn't work reliantly for this case
  assertTrue("Check last modified date preserved",
    testFile1.lastModified() == destination.lastModified());*/
  try {
    FileUtils.copyFileToDirectory(destination, directory);
    fail("Should not be able to copy a file into the same directory as itself");
  } catch (final IOException ioe) {
    //we want that, cannot copy to the same directory as the original file
  }
}

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

@Test
public void shouldNotFailToRegisterOtherClassesIfAClassCannotBeLoadedBecauseOfWrongPath() throws Exception {
  File bundleWithActivator = createBundleWithActivator(BUNDLE_DIR_WHICH_HAS_PROPER_ACTIVATOR, DummyTestPlugin.class);
  File sourceClassFile = new File(bundleWithActivator, "com/thoughtworks/go/plugin/activation/test/DummyTestPlugin.class");
  File destinationFile = new File(bundleWithActivator, "ABC-DEF/com/thoughtworks/go/plugin/activation/test/");
  FileUtils.copyFileToDirectory(sourceClassFile, destinationFile, true);
  Bundle bundle = installBundleFoundInDirectory(bundleWithActivator);
  assertThat(bundle.getState(), is(Bundle.UNINSTALLED));
}

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

@Test
public void read_download_folder() throws Exception {
 pluginDownloader.start();
 assertThat(noDownloadedFiles()).isZero();
 copyFileToDirectory(TestProjectUtils.jarOf("test-base-plugin"), downloadDir);
 assertThat(pluginDownloader.getDownloadedPlugins()).hasSize(1);
 PluginInfo info = pluginDownloader.getDownloadedPlugins().iterator().next();
 assertThat(info.getKey()).isEqualTo("testbase");
 assertThat(info.getName()).isEqualTo("Base Plugin");
 assertThat(info.getVersion()).isEqualTo(Version.create("0.1-SNAPSHOT"));
 assertThat(info.getMainClass()).isEqualTo("BasePlugin");
}

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

if (!exclusions.contains(artifact.getGroupId())) {
 log.info("Adding file [%s] at [%s]", artifact.getFile().getName(), toLocation.getAbsolutePath());
 FileUtils.copyFileToDirectory(artifact.getFile(), toLocation);
} else {
 log.debug("Skipped Artifact[%s]", artifact);

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

@Override
protected void onSetUp(SystemTestData testData) throws Exception {
  super.onSetUp(testData);
  testData.addStyle("relative", "se_relativepath.sld", ResourcePoolTest.class, getCatalog());
  testData.addStyle(
      "relative_protocol",
      "se_relativepath_protocol.sld",
      ResourcePoolTest.class,
      getCatalog());
  testData.addStyle(HUMANS, "humans.sld", ResourcePoolTest.class, getCatalog());
  testData.addStyle(EXTERNAL_ENTITIES, "externalEntities.sld", TestData.class, getCatalog());
  StyleInfo style = getCatalog().getStyleByName("relative");
  style.setFormatVersion(new Version("1.1.0"));
  getCatalog().save(style);
  style = getCatalog().getStyleByName(HUMANS);
  style.setFormatVersion(new Version("1.1.0"));
  getCatalog().save(style);
  File images = new File(testData.getDataDirectoryRoot(), "styles/images");
  assertTrue(images.mkdir());
  File image = new File("./src/test/resources/org/geoserver/catalog/rockFillSymbol.png");
  assertTrue(image.exists());
  FileUtils.copyFileToDirectory(image, images);
  rockFillSymbolFile = new File(images, image.getName()).getCanonicalFile();
  testData.addRasterLayer(
      TIMERANGES, "timeranges.zip", null, null, SystemTestData.class, getCatalog());
  FileUtils.copyFileToDirectory(
      new File("./src/test/resources/geoserver-environment.properties"),
      testData.getDataDirectoryRoot());
}

相关文章

微信公众号

最新文章

更多

FileUtils类方法