java.nio.file.Files.list()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(8.9k)|赞(0)|评价(0)|浏览(329)

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

Files.list介绍

暂无

代码示例

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

public static Path[] listFiles(Path path) throws IOException {
 try (Stream<Path> list = Files.list(path)) {
  return list.toArray(Path[]::new);
 }
}

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

/**
 * Count the number of files and directories, contained in the given {@link Path}, which must be a directory.
 * @param dir The directory whose contents to count.
 * @return The number of files and directories in the given directory.
 * @throws NotDirectoryException If the given {@link Path} is not a directory. This exception is an optionally
 * specific exception. {@link IOException} might be thrown instead.
 * @throws IOException If the given directory could not be opened for some reason.
 */
public static long countFilesInDirectoryPath( Path dir ) throws IOException
{
  try ( Stream<Path> listing = Files.list( dir ) )
  {
    return listing.count();
  }
}

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

public static Path[] listFiles(Path path, final Predicate<Path> filter) throws IOException {
 try (Stream<Path> list = Files.list(path)) {
  return list.filter(filter).toArray(Path[]::new);
 }
}

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

private static boolean isIndexDirectory( Path path ) throws IOException
{
  try ( Stream<Path> pathStream = Files.list( path ) )
  {
    return pathStream.anyMatch( child -> child.getFileName().toString().startsWith( SEGMENTS_FILE_NAME_PREFIX ) );
  }
}

代码示例来源:origin: siacs/Conversations

@Override
public final Set<String> keySet() {
  try (final Stream<Path> files = Files.list(cacheDirectory)) {
    return Collections.unmodifiableSet(files.map(Path::getFileName).map(Path::toString).collect(Collectors.toSet()));
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}

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

@Override
public File[] listFiles( File directory )
{
  try ( Stream<Path> listing = Files.list( path( directory ) ) )
  {
    return listing.map( Path::toFile ).toArray( File[]::new );
  }
  catch ( IOException e )
  {
    return null;
  }
}

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

static Collection<String> getLocalizedUsers(Path localBaseDir) throws IOException {
  Path userCacheDir = getUserCacheDir(localBaseDir);
  if (!Files.exists(userCacheDir)) {
    return Collections.emptyList();
  }
  return Files.list(userCacheDir).map((p) -> p.getFileName().toString()).collect(Collectors.toList());
}

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

private static List<String> readKeysFromDir(Path dir) throws IOException {
  if (!Files.exists(dir)) {
    return Collections.emptyList();
  }
  return Files.list(dir)
        .map((p) -> p.getFileName().toString())
        .filter((name) -> name.toLowerCase().endsWith(CURRENT_BLOB_SUFFIX))
        .map((key) -> {
          int p = key.lastIndexOf('.');
          if (p > 0) {
            key = key.substring(0, p);
          }
          return key;
        })
        .collect(Collectors.toList());
}

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

@Override
public File[] listFiles( File directory, final FilenameFilter filter )
{
  try ( Stream<Path> listing = Files.list( path( directory ) ) )
  {
    return listing
        .filter( entry -> filter.accept( entry.getParent().toFile(), entry.getFileName().toString() ) )
        .map( Path::toFile )
        .toArray( File[]::new );
  }
  catch ( IOException e )
  {
    return null;
  }
}

代码示例来源:origin: twosigma/beakerx

private Map<Path, String> getPaths(String pathWithWildcard) {
 String pathWithoutWildcards = pathWithWildcard.replace("*", "");
 try {
  return Files.list(Paths.get(pathWithoutWildcards))
      .filter(path -> path.toString().toLowerCase().endsWith(".jar"))
      .collect(Collectors.toMap(p -> p, o -> o.getFileName().toString()));
 } catch (IOException e) {
  throw new IllegalStateException("Cannot create any jars files in selected path");
 }
}

代码示例来源:origin: twosigma/beakerx

private Map<String, Path> jarsFromRepo() {
 try {
  List<Path> collect = Files.list(Paths.get(pathToMavenRepo)).collect(Collectors.toList());
  return collect.stream().collect(Collectors.toMap(x -> x.getFileName().toString(), x -> x));
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: MovingBlocks/Terasology

private static List<Path> getAllPathsToFilesInFolder(final Path dirPath) {
  // create folder if not exists yet
  createDirectory(dirPath);
  try (Stream<Path> stream = Files.list(dirPath).filter(Files::isRegularFile)) {
    return stream.collect(Collectors.toList());
  } catch (Exception e) {
    logger.warn("Can't correctly read files from {}", dirPath);
    return Collections.emptyList();
  }
}

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

private void removeOrMakeRemovableThenRemove(@Nonnull Path path) throws IOException {
  pathChecker.check(path);
  try {
    Files.deleteIfExists(path);
  } catch (IOException e) {
    makeRemovable(path);
    try {
      Files.deleteIfExists(path);
    } catch (IOException e2) {
      // see https://java.net/projects/hudson/lists/users/archive/2008-05/message/357
      // I suspect other processes putting files in this directory
      if (Files.isDirectory(path)) {
        List<String> entries;
        try (Stream<Path> children = Files.list(path)) {
          entries = children.map(Path::toString).collect(Collectors.toList());
        }
        throw new CompositeIOException("Unable to remove directory " + path + " with directory contents: " + entries, e, e2);
      }
      throw new CompositeIOException("Unable to remove file " + path, e, e2);
    }
  }
}

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

private static Optional<Path> findExternalizedCheckpoint(File checkpointDir, JobID jobId) throws IOException {
  try (Stream<Path> checkpoints = Files.list(checkpointDir.toPath().resolve(jobId.toString()))) {
    return checkpoints
      .filter(path -> path.getFileName().toString().startsWith("chk-"))
      .filter(path -> {
        try (Stream<Path> checkpointFiles = Files.list(path)) {
          return checkpointFiles.anyMatch(child -> child.getFileName().toString().contains("meta"));
        } catch (IOException ignored) {
          return false;
        }
      })
      .findAny();
  }
}

代码示例来源:origin: MovingBlocks/Terasology

private void setCurrentDirectory(Path newPath) {
  try (Stream<Path> stream = Files.list(newPath)) {
    loadDirectoryContents(stream);
    currentPath = newPath;
  } catch (AccessDeniedException ex) {
    showDirectoryAccessErrorMessage(translationSystem.translate("${engine:menu#file-picker-access-denied-to}") + newPath);
  } catch (IOException ex) {
    showDirectoryAccessErrorMessage(ex.toString());
  }
}

代码示例来源:origin: confluentinc/ksql

private static Stream<Path> findTestSchemas() {
  try {
   final Path resourceRoot = getResourceRoot();
   return Files.list(resourceRoot)
     .filter(path -> path.toString().endsWith(".avro"));

  } catch (final Exception e) {
   throw new RuntimeException("failed to find test schemas", e);
  }
 }
}

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

@Test
  public void shouldExtractJars() throws Exception {
    File sourceFile = new File(PATH_WITH_HASHES + "test-agent.jar");
    File outputTmpDir = temporaryFolder.newFolder();
    Set<File> files = new HashSet<>(JarUtil.extractFilesInLibDirAndReturnFiles(sourceFile, jarEntry -> jarEntry.getName().endsWith(".class"), outputTmpDir));

    Set<File> actualFiles = Files.list(outputTmpDir.toPath()).map(Path::toFile).collect(Collectors.toSet());

    assertEquals(files, actualFiles);
    assertEquals(files.size(), 2);
    Set<String> fileNames = files.stream().map(File::getName).collect(Collectors.toSet());
    assertEquals(fileNames, new HashSet<>(Arrays.asList("ArgPrintingMain.class", "HelloWorldStreamWriter.class")));
  }
}

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

@Test
public void testStopJobAfterSavepoint() throws Exception {
  setUpWithCheckpointInterval(10L);
  final String savepointLocation = cancelWithSavepoint();
  final JobStatus jobStatus = clusterClient.getJobStatus(jobGraph.getJobID()).get();
  assertThat(jobStatus, isOneOf(JobStatus.CANCELED, JobStatus.CANCELLING));
  final List<Path> savepoints;
  try (Stream<Path> savepointFiles = Files.list(savepointDirectory)) {
    savepoints = savepointFiles.map(Path::getFileName).collect(Collectors.toList());
  }
  assertThat(savepoints, hasItem(Paths.get(savepointLocation).getFileName()));
}

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

@Test
public void testStopJobAfterSavepointWithDeactivatedPeriodicCheckpointing() throws Exception {
  // set checkpointInterval to Long.MAX_VALUE, which means deactivated checkpointing
  setUpWithCheckpointInterval(Long.MAX_VALUE);
  final String savepointLocation = cancelWithSavepoint();
  final JobStatus jobStatus = clusterClient.getJobStatus(jobGraph.getJobID()).get(60, TimeUnit.SECONDS);
  assertThat(jobStatus, isOneOf(JobStatus.CANCELED, JobStatus.CANCELLING));
  final List<Path> savepoints;
  try (Stream<Path> savepointFiles = Files.list(savepointDirectory)) {
    savepoints = savepointFiles.map(Path::getFileName).collect(Collectors.toList());
  }
  assertThat(savepoints, hasItem(Paths.get(savepointLocation).getFileName()));
}

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

@Test
  public void testDeleteApplicationFiles() throws Exception {
    final Path applicationFilesDir = temporaryFolder.newFolder(".flink").toPath();
    Files.createFile(applicationFilesDir.resolve("flink.jar"));
    try (Stream<Path> files = Files.list(temporaryFolder.getRoot().toPath())) {
      assertThat(files.count(), equalTo(1L));
    }
    try (Stream<Path> files = Files.list(applicationFilesDir)) {
      assertThat(files.count(), equalTo(1L));
    }

    Utils.deleteApplicationFiles(Collections.singletonMap(
      YarnConfigKeys.FLINK_YARN_FILES,
      applicationFilesDir.toString()));
    try (Stream<Path> files = Files.list(temporaryFolder.getRoot().toPath())) {
      assertThat(files.count(), equalTo(0L));
    }
  }
}

相关文章

微信公众号

最新文章

更多