java.io.File.toPath()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(10.7k)|赞(0)|评价(0)|浏览(708)

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

File.toPath介绍

暂无

代码示例

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

private void addEmptyUsernameIfExists(Map<String, File> users) throws IOException {
  File emptyUsernameConfigFile = new File(usersDirectory, User.CONFIG_XML);
  if (emptyUsernameConfigFile.exists()) {
    File newEmptyUsernameDirectory = new File(usersDirectory, EMPTY_USERNAME_DIRECTORY_NAME);
    Files.createDirectory(newEmptyUsernameDirectory.toPath());
    File newEmptyUsernameConfigFile = new File(newEmptyUsernameDirectory, User.CONFIG_XML);
    Files.move(emptyUsernameConfigFile.toPath(), newEmptyUsernameConfigFile.toPath());
    users.put("", newEmptyUsernameDirectory);
  }
}

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

/**
 * Gets the OutputStream to write to the file.
 */
public OutputStream write() throws IOException {
  if(gz.exists())
    gz.delete();
  try {
    return Files.newOutputStream(file.toPath());
  } catch (InvalidPathException e) {
    throw new IOException(e);
  }
}

代码示例来源:origin: stackoverflow.com

long bytes = java.nio.file.Files.copy( 
        new java.io.File("<filepath1>").toPath(), 
        new java.io.File("<filepath2>").toPath(),
        java.nio.file.StandardCopyOption.REPLACE_EXISTING,
        java.nio.file.StandardCopyOption.COPY_ATTRIBUTES,
        java.nio.file.LinkOption.NOFOLLOW_LINKS);

代码示例来源:origin: skylot/jadx

public static boolean isCaseSensitiveFS(File testDir) {
  if (testDir != null) {
    File caseCheckUpper = new File(testDir, "CaseCheck");
    File caseCheckLow = new File(testDir, "casecheck");
    try {
      makeDirs(testDir);
      if (caseCheckUpper.createNewFile()) {
        boolean caseSensitive = !caseCheckLow.exists();
        LOG.debug("Filesystem at {} is {}case-sensitive", testDir.getAbsolutePath(),
            (caseSensitive ? "" : "NOT "));
        return caseSensitive;
      } else {
        LOG.debug("Failed to create file: {}", caseCheckUpper.getAbsolutePath());
      }
    } catch (Exception e) {
      LOG.debug("Failed to detect filesystem case-sensitivity by file creation", e);
    } finally {
      try {
        Files.deleteIfExists(caseCheckUpper.toPath());
        Files.deleteIfExists(caseCheckLow.toPath());
      } catch (Exception e) {
        // ignore
      }
    }
  }
  return IOCase.SYSTEM.isCaseSensitive();
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testRunVerticleWithoutMainVerticleInManifestButWithCustomCommand() throws Exception {
 // Copy the right manifest
 File manifest = new File("target/test-classes/META-INF/MANIFEST-Launcher-Default-Command.MF");
 if (!manifest.isFile()) {
  throw new IllegalStateException("Cannot find the MANIFEST-Default-Command.MF file");
 }
 File target = new File("target/test-classes/META-INF/MANIFEST.MF");
 Files.copy(manifest.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
 Launcher launcher = new Launcher();
 HelloCommand.called = false;
 String[] args = {"--name=vert.x"};
 launcher.dispatch(args);
 assertWaitUntil(() -> HelloCommand.called);
}

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

@Test
public void testTodaysFilesPickedUp() throws IOException {
  final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
  final String dirStruc = sdf.format(new Date());
  final File directory = new File("target/test/data/in/" + dirStruc);
  deleteDirectory(directory);
  assertTrue("Unable to create test data directory " + directory.getAbsolutePath(), directory.exists() || directory.mkdirs());
  final File inFile = new File("src/test/resources/hello.txt");
  final Path inPath = inFile.toPath();
  final File destFile = new File(directory, inFile.getName());
  final Path targetPath = destFile.toPath();
  Files.copy(inPath, targetPath);
  final TestRunner runner = TestRunners.newTestRunner(new GetFile());
  runner.setProperty(GetFile.DIRECTORY, "target/test/data/in/${now():format('yyyy/MM/dd')}");
  runner.run();
  runner.assertAllFlowFilesTransferred(GetFile.REL_SUCCESS, 1);
  final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(GetFile.REL_SUCCESS);
  successFiles.get(0).assertContentEquals("Hello, World!".getBytes("UTF-8"));
}

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

@Test
public void withFiles_savedToLocatorSpecifiedRelativeDir() throws Exception {
 String[] extensions = {"zip"};
 Path workingDirPath = getWorkingDirectory().toPath();
 Path subdirPath = workingDirPath.resolve("some").resolve("test").resolve("directory");
 Path relativeDir = workingDirPath.relativize(subdirPath);
 // Expects locator to produce file in own working directory when connected via JMX
 gfshConnector.executeCommand("export logs --dir=" + relativeDir.toString());
 assertThat(listFiles(getWorkingDirectory(), extensions, false)).isEmpty();
 assertThat(listFiles(getWorkingDirectory(), extensions, true)).isNotEmpty();
 assertThat(listFiles(subdirPath.toFile(), extensions, false)).isNotEmpty();
}

代码示例来源:origin: stackoverflow.com

List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
  Files.copy(file.toPath(),
    (new File(path + file.getName())).toPath(),
    StandardCopyOption.REPLACE_EXISTING);
}

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

/**
 * Utility method that copy a file from its current location to the
 * provided target directory.
 *
 * @param file file that needs to be copied.
 * @param targetDirectory the destination directory
 * @throws IOException
 */
public static void copyFileToDirectory( File file, File targetDirectory ) throws IOException
{
  if ( !targetDirectory.exists() )
  {
    Files.createDirectories( targetDirectory.toPath() );
  }
  if ( !targetDirectory.isDirectory() )
  {
    throw new IllegalArgumentException(
        "Move target must be a directory, not " + targetDirectory );
  }
  File target = new File( targetDirectory, file.getName() );
  copyFile( file, target );
}

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

sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.lpVerb = "runas";
sei.lpFile = jenkinsExe.getAbsolutePath();
sei.lpParameters = "/redirect redirect.log "+command;
sei.lpDirectory = pwd.getAbsolutePath();
sei.nShow = SW_HIDE;
if (!Shell32.INSTANCE.ShellExecuteEx(sei))
  return Kernel32Utils.waitForExitProcess(sei.hProcess);
} finally {
  try (InputStream fin = Files.newInputStream(new File(pwd,"redirect.log").toPath())) {
    IOUtils.copy(fin, out.getLogger());
  } catch (InvalidPathException e) {

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

@Override
public Path discover(final String cgroup)
{
 Preconditions.checkNotNull(cgroup, "cgroup required");
 final File procMounts = new File(procDir, "mounts");
 final File pidCgroups = new File(procDir, "cgroup");
 final PidCgroupEntry pidCgroupsEntry = getCgroupEntry(pidCgroups, cgroup);
 final ProcMountsEntry procMountsEntry = getMountEntry(procMounts, cgroup);
 final File cgroupDir = new File(
   procMountsEntry.path.toString(),
   pidCgroupsEntry.path.toString()
 );
 if (cgroupDir.exists() && cgroupDir.isDirectory()) {
  return cgroupDir.toPath();
 }
 throw new RE("Invalid cgroup directory [%s]", cgroupDir);
}

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

private void createTempLauncherJar() {
  try {
    inUseLauncher.getParentFile().mkdirs();
    Files.copy(new File(Downloader.AGENT_LAUNCHER).toPath(), inUseLauncher.toPath());
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  LauncherTempFileHandler.startTempFileReaper();
}

代码示例来源:origin: pxb1988/dex2jar

@Test
public void t() throws Exception {
  File dir = new File("../dex-translator/src/test/resources/dexes");
  File[] fs = dir.listFiles();
  if (fs != null) {
    for (File f : fs) {
      if (f.getName().endsWith(".dex") || f.getName().endsWith(".apk")) {
        dotest(f.toPath());
      }
    }
  }
}

代码示例来源:origin: org.testng/testng

protected PrintWriter createWriter(String outdir) throws IOException {
  new File(outdir).mkdirs();
  String jvmArg = System.getProperty(JVM_ARG);
  if (jvmArg != null && !jvmArg.trim().isEmpty()) {
    fileName = jvmArg;
  }
  return new PrintWriter(newBufferedWriter(new File(outdir, fileName).toPath(), UTF_8));
}

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

public static void moveFile(File src, File targetDirectory) throws IOException {
  if (!src.renameTo(new File(targetDirectory, src.getName()))) {
    // If rename fails we must do a true deep copy instead.
    Path sourcePath = src.toPath();
    Path targetDirPath = targetDirectory.toPath();
    try {
      Files.move(sourcePath, targetDirPath.resolve(sourcePath.getFileName()), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException ex) {
      throw new IOException("Failed to move " + src + " to " + targetDirectory + " - " + ex.getMessage());
    }
  }
}

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

@Test
public void mustCountDirectoryContents() throws Exception
{
  File dir = directory( "dir" );
  File file = new File( dir, "file" );
  File subdir = new File( dir, "subdir" );
  file.createNewFile();
  subdir.mkdirs();
  assertThat( FileUtils.countFilesInDirectoryPath( dir.toPath() ), is( 2L ) );
}

代码示例来源:origin: eclipse-vertx/vert.x

private String createClassOutsideClasspath(String className) throws Exception {
 File dir = Files.createTempDirectory("vertx").toFile();
 dir.deleteOnExit();
 File source = new File(dir, className + ".java");
 Files.write(source.toPath(), ("public class " + className + " extends io.vertx.core.AbstractVerticle {} ").getBytes());
 URLClassLoader loader = new URLClassLoader(new URL[]{dir.toURI().toURL()}, Thread.currentThread().getContextClassLoader());
 CompilingClassLoader compilingClassLoader = new CompilingClassLoader(loader, className + ".java");
 compilingClassLoader.loadClass(className);
 byte[] bytes = compilingClassLoader.getClassBytes(className);
 assertNotNull(bytes);
 File classFile = new File(dir, className + ".class");
 Files.write(classFile.toPath(), bytes);
 return dir.getAbsolutePath();
}

代码示例来源:origin: OpenHFT/Chronicle-Queue

@Before
public void setUp() throws Exception {
  testDirectory = testDirectory();
  testDirectory.mkdirs();
  File tableFile = new File(testDirectory, "dir-list" + SingleTableStore.SUFFIX);
  tablestore = SingleTableBuilder.
      binary(tableFile, Metadata.NoMeta.INSTANCE).build();
  listing = new TableDirectoryListing(tablestore,
      testDirectory.toPath(),
      f -> Integer.parseInt(f.getName().split("\\.")[0]),
      false);
  listing.init();
  tempFile = File.createTempFile("foo", "bar");
  tempFile.deleteOnExit();
}

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

public void create() {
  checkFilesAccessibility(bundledPlugins, externalPlugins);
  reset();
  MessageDigest md5Digest = DigestUtils.getMd5Digest();
  try (ZipOutputStream zos = new ZipOutputStream(new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(destZipFile)), md5Digest))) {
    for (GoPluginDescriptor agentPlugins : agentPlugins()) {
      String zipEntryPrefix = "external/";
      if (agentPlugins.isBundledPlugin()) {
        zipEntryPrefix = "bundled/";
      }
      zos.putNextEntry(new ZipEntry(zipEntryPrefix + new File(agentPlugins.pluginFileLocation()).getName()));
      Files.copy(new File(agentPlugins.pluginFileLocation()).toPath(), zos);
      zos.closeEntry();
    }
  } catch (Exception e) {
    LOG.error("Could not create zip of plugins for agent to download.", e);
  }
  md5DigestOfPlugins = Hex.encodeHexString(md5Digest.digest());
}

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

@Test
public void testSimpleProc()
{
 Assert.assertEquals(
   new File(
     cgroupDir,
     "cpu,cpuacct/system.slice/some.service/f12ba7e0-fa16-462e-bb9d-652ccc27f0ee"
   ).toPath(),
   discoverer.discover("cpu")
 );
}

相关文章

微信公众号

最新文章

更多