Java Code Examples for java.nio.file.Files.list()

The following are Jave code examples for showing how to use list() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: powsybl-core   File: Importers.java   View Source Code Vote up 6 votes
private static void importAll(Path parent, Importer importer, List<ReadOnlyDataSource> dataSources) throws IOException {
    if (Files.isDirectory(parent)) {
        try (Stream<Path> stream = Files.list(parent)) {
            stream.sorted().forEach(child -> {
                if (Files.isDirectory(child)) {
                    try {
                        importAll(child, importer, dataSources);
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                } else {
                    addDataSource(parent, child, importer, dataSources);
                }
            });
        }
    } else {
        if (parent.getParent() != null) {
            addDataSource(parent.getParent(), parent, importer, dataSources);
        }
    }
}
 
Example 2
Project: presto-manager   File: AgentFileUtils.java   View Source Code Vote up 6 votes
public static List<String> getFileNameList(Path path)
        throws IOException
{
    ImmutableList<String> fileNames;
    try (Stream<Path> stream = Files.list(path)) {
        fileNames = stream.filter(Files::isRegularFile)
                .map(Path::getFileName).map(Path::toString)
                .collect(toImmutableList());
    }
    return fileNames;
}
 
Example 3
Project: openjdk-jdk10   File: Basic.java   View Source Code Vote up 6 votes
@Test(dataProvider = "knownDirectories")
public void testKnownDirectories(String path, boolean theDefault) throws Exception {
    if (isExplodedBuild && !theDefault) {
        System.out.println("Skip testKnownDirectories with non-default FileSystem");
        return;
    }

    FileSystem fs = selectFileSystem(theDefault);
    Path dir = fs.getPath(path);

    assertTrue(Files.isDirectory(dir));

    // directory should not be empty
    try (Stream<Path> stream = Files.list(dir)) {
        assertTrue(stream.count() > 0L);
    }
    try (Stream<Path> stream = Files.walk(dir)) {
        assertTrue(stream.count() > 0L);
    }
}
 
Example 4
Project: openjdk-jdk10   File: JShellTool.java   View Source Code Vote up 6 votes
private static CompletionProvider fileCompletions(Predicate<Path> accept) {
    return (code, cursor, anchor) -> {
        int lastSlash = code.lastIndexOf('/');
        String path = code.substring(0, lastSlash + 1);
        String prefix = lastSlash != (-1) ? code.substring(lastSlash + 1) : code;
        Path current = toPathResolvingUserHome(path);
        List<Suggestion> result = new ArrayList<>();
        try (Stream<Path> dir = Files.list(current)) {
            dir.filter(f -> accept.test(f) && f.getFileName().toString().startsWith(prefix))
               .map(f -> new ArgSuggestion(f.getFileName() + (Files.isDirectory(f) ? "/" : "")))
               .forEach(result::add);
        } catch (IOException ex) {
            //ignore...
        }
        if (path.isEmpty()) {
            StreamSupport.stream(FileSystems.getDefault().getRootDirectories().spliterator(), false)
                         .filter(root -> Files.exists(root))
                         .filter(root -> accept.test(root) && root.toString().startsWith(prefix))
                         .map(root -> new ArgSuggestion(root.toString()))
                         .forEach(result::add);
        }
        anchor[0] = path.length();
        return result;
    };
}
 
Example 5
Project: openjdk-jdk10   File: CommandCompletionTest.java   View Source Code Vote up 5 votes
@Test
public void testUserHome() throws IOException {
    List<String> completions;
    Path home = Paths.get(System.getProperty("user.home"));
    try (Stream<Path> content = Files.list(home)) {
        completions = content.filter(CLASSPATH_FILTER)
                             .map(file -> file.getFileName().toString() + (Files.isDirectory(file) ? "/" : ""))
                             .sorted()
                             .collect(Collectors.toList());
    }
    testNoStartUp(
            a -> assertCompletion(a, "/env --class-path ~/|", false, completions.toArray(new String[completions.size()]))
    );
}
 
Example 6
Project: openjdk-jdk10   File: Locations.java   View Source Code Vote up 5 votes
private void addDirectory(Path dir, boolean warn) {
    if (!Files.isDirectory(dir)) {
        if (warn) {
            log.warning(Lint.LintCategory.PATH,
                        Warnings.DirPathElementNotFound(dir));
        }
        return;
    }

    try (Stream<Path> s = Files.list(dir)) {
        s.filter(Locations.this::isArchive)
                .forEach(dirEntry -> addFile(dirEntry, warn));
    } catch (IOException ignore) {
    }
}
 
Example 7
Project: elasticsearch_my   File: SharedClusterSnapshotRestoreIT.java   View Source Code Vote up 5 votes
public void testSnapshotWithMissingShardLevelIndexFile() throws Exception {
    Path repo = randomRepoPath();
    logger.info("-->  creating repository at {}", repo.toAbsolutePath());
    assertAcked(client().admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(
        Settings.builder().put("location", repo).put("compress", false)));

    createIndex("test-idx-1", "test-idx-2");
    logger.info("--> indexing some data");
    indexRandom(true,
        client().prepareIndex("test-idx-1", "doc").setSource("foo", "bar"),
        client().prepareIndex("test-idx-2", "doc").setSource("foo", "bar"));

    logger.info("--> creating snapshot");
    client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-1")
        .setWaitForCompletion(true).setIndices("test-idx-*").get();

    logger.info("--> deleting shard level index file");
    try (Stream<Path> files = Files.list(repo.resolve("indices"))) {
        files.forEach(indexPath ->
            IOUtils.deleteFilesIgnoringExceptions(indexPath.resolve("0").resolve("index-0"))
        );
    }

    logger.info("--> creating another snapshot");
    CreateSnapshotResponse createSnapshotResponse =
        client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-2")
            .setWaitForCompletion(true).setIndices("test-idx-1").get();
    assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
    assertEquals(createSnapshotResponse.getSnapshotInfo().successfulShards(), createSnapshotResponse.getSnapshotInfo().totalShards());

    logger.info("--> restoring the first snapshot, the repository should not have lost any shard data despite deleting index-N, " +
                    "because it should have iterated over the snap-*.data files as backup");
    client().admin().indices().prepareDelete("test-idx-1", "test-idx-2").get();
    RestoreSnapshotResponse restoreSnapshotResponse =
        client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-1").setWaitForCompletion(true).get();
    assertEquals(0, restoreSnapshotResponse.getRestoreInfo().failedShards());
}
 
Example 8
Project: csap-core   File: SimpleTests.java   View Source Code Vote up 5 votes
@Test
public void verifyFileMatching ()
		throws Exception {
	try (Stream<Path> pathStream = Files.list( new File( "/java" ).toPath() )) {
		Optional<Path> deploymentCheck = pathStream
			.filter( path -> path.getFileName().toString().endsWith( ".bat" ) )
			.findFirst();

		// logger.info( "object: {} : value: {}", deploymentCheck,
		// deploymentCheck.get() );
	}

}
 
Example 9
Project: openjdk-jdk10   File: CommandCompletionTest.java   View Source Code Vote up 5 votes
private List<String> listFiles(Path path, Predicate<? super Path> filter) throws IOException {
    try (Stream<Path> stream = Files.list(path)) {
        return stream.filter(filter)
                     .map(p -> p.getFileName().toString() + (Files.isDirectory(p) ? "/" : ""))
                     .sorted()
                     .collect(Collectors.toList());
    }
}
 
Example 10
Project: rookit-core   File: TrackParserGenerator.java   View Source Code Vote up 5 votes
private Stream<Path> list(Path source) {
	try {
		return Files.list(source);
	} catch (IOException e) {
		validator.handleIOException(e);
		return null;
	}
}
 
Example 11
Project: tg-eventstore   File: FlatFilesystemEventStreamWriter.java   View Source Code Vote up 5 votes
private long currentVersion(StreamId streamId) {
    try (Stream<Path> stream = Files.list(directory)) {
        return stream
                .filter(p -> p.getFileName().toString().endsWith(dataSuffix))
                .filter(p -> FilenameCodec.parse(p, (timestamp, fileStreamId, eventNumber, eventType) -> fileStreamId.equals(streamId)))
                .count() - 1;
    } catch (IOException e) {
        throw new RuntimeException("Unable to count files in " + directory);
    }
}
 
Example 12
Project: tg-eventstore   File: FlatFilesystemEventStreamWriter.java   View Source Code Vote up 5 votes
private long currentGlobalVersion() {
    try (Stream<Path> stream = Files.list(directory)) {
        return stream.filter(p -> p.getFileName().toString().endsWith(dataSuffix)).count();
    } catch (IOException e) {
        throw new RuntimeException("Unable to count files in " + directory);
    }
}
 
Example 13
Project: tg-eventstore   File: FlatFilesystemEventReader.java   View Source Code Vote up 5 votes
boolean streamExists(StreamId streamId) {
    try (Stream<Path> stream = Files.list(directory)) {
        return stream
                .filter(p -> p.getFileName().toString().endsWith(dataSuffix))
                .anyMatch(p -> FilenameCodec.parse(p, (timestamp, fileStreamId, eventNumber, eventType) -> fileStreamId.equals(streamId)));
    } catch (IOException e) {
        throw new RuntimeException("Unable to count files in " + directory);
    }
}
 
Example 14
Project: monarch   File: MTableDUnitConfigFramework.java   View Source Code Vote up 5 votes
private void truncateStoreFiles(String storeName) {
  try {
    Stream<Path> list = Files.list(new File(".").toPath());
    Object[] paths = list.toArray();
    for (Object path : paths) {
      if (path.toString().contains(storeName)) {
        Files.write((Path) path, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);
      }
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 15
Project: instalint   File: PluginFileLocator.java   View Source Code Vote up 5 votes
static Path findFirst(Path basedir, String glob) throws IOException {
  PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);
  try (Stream<Path> stream = Files.list(basedir)) {
    return stream
      .filter(matcher::matches)
      .findFirst()
      .orElseThrow(() -> new FileNotFoundException(basedir + "/.../" + glob));
  }
}
 
Example 16
Project: openjdk-jdk10   File: DependenciesTest.java   View Source Code Vote up 5 votes
void run() throws IOException {
    Path src = Paths.get(System.getProperty("test.src"), "tests");

    try (Stream<Path> tests = Files.list(src)) {
        tests.map(p -> Files.isRegularFile(p) ? Stream.of(p) : silentWalk(p))
             .forEach(this :: runTest);
    }
}
 
Example 17
Project: ocraft-s2client   File: S2Controller.java   View Source Code Vote up 5 votes
private Function<Path, String> toNewestExeFile() {
    return path -> {
        try (Stream<Path> exes = Files.list(path)) {
            return exes.sorted(reverseOrder()).findFirst()
                    .map(Path::getFileName)
                    .map(Path::toString)
                    .orElseThrow(required("exe file name"));
        } catch (IOException e) {
            log.debug("Newest exe file not found.", e);
            throw new StarCraft2LaunchException("Newest exe file not found.", e);
        }
    };
}
 
Example 18
Project: chipKIT-importer   File: ChipKitProjectImporter.java   View Source Code Vote up 4 votes
private Stream<Path> getLibraryDirPaths( boolean main ) throws IOException {
    Stream <Path> libStream = copyingFiles ? Files.list( getLibraryDirectoryPath() ) : sourceLibraryPaths.stream();
    return libStream
        .filter( p -> Files.isDirectory(p) )
        .filter( p -> main == mainLibraryNames.contains(p.getFileName().toString()) );
}
 
Example 19
Project: openjdk-jdk10   File: CreateSymbolsTestImpl.java   View Source Code Vote up 4 votes
private static String computeClassPath(Path classes, String version) throws IOException {
    try (Stream<Path> elements = Files.list(classes)) {
        return elements.map(el -> el.toAbsolutePath().toString())
                       .collect(Collectors.joining(File.pathSeparator));
    }
}
 
Example 20
Project: mpd-tools   File: MPDParserTest.java   View Source Code Vote up 4 votes
@Parameters
public static List<Path> params() throws IOException {
    try (Stream<Path> paths = Files.list(Paths.get("src/test/resources/vectors/"))) {
        return paths.collect(Collectors.toList());
    }
}