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

The following are Jave code examples for showing how to use find() 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: Matcher   File: Matcher.java   View Source Code Vote up 6 votes
private static List<Path> resolvePaths(List<Path> inputDirs, List<InputFile> inputFiles) throws IOException {
	List<Path> ret = new ArrayList<>(inputFiles.size());

	for (InputFile inputFile : inputFiles) {
		boolean found = false;

		for (Path inputDir : inputDirs) {
			try (Stream<Path> matches = Files.find(inputDir, Integer.MAX_VALUE, (path, attr) -> inputFile.equals(path), FileVisitOption.FOLLOW_LINKS)) {
				Path file = matches.findFirst().orElse(null);

				if (file != null) {
					ret.add(file);
					found = true;
					break;
				}
			} catch (UncheckedIOException e) {
				throw e.getCause();
			}
		}

		if (!found) throw new IOException("can't find input "+inputFile.getFileName());
	}

	return ret;
}
 
Example 2
Project: mot-automated-testsuite   File: DataServerManager.java   View Source Code Vote up 6 votes
/**
 * Calculates the server classpath, which is a colon-delimited string of directories and .jar files.
 * @param baseLibDir    The base directory of server libs and classes
 * @return The classpath
 */
private static String calculateServerClasspath(String baseLibDir) {
    try {
        Path baseLibPath = Paths.get(baseLibDir).toAbsolutePath().normalize();
        Stream<Path> jars = Files.find(baseLibPath, 1, (path, attrs) -> path.toString().endsWith(".jar"));
        StringJoiner joiner = new StringJoiner(":");

        // server libs directory (containing the server Java classes)
        joiner.add(baseLibPath.toString());

        // all .jar files in the same directory
        jars.forEach((path) -> joiner.add(path.toString()));

        return joiner.toString();

    } catch (IOException ex) {
        String message = "Error resolving server base lib dir: " + ex.getMessage();
        logger.error(message, ex);
        throw new IllegalArgumentException(message, ex);
    }
}
 
Example 3
Project: Matcher   File: MappingReader.java   View Source Code Vote up 5 votes
public static void readEnigma(Path dir, IMappingAcceptor mappingAcceptor) throws IOException {
	try (Stream<Path> stream = Files.find(dir,
			Integer.MAX_VALUE,
			(path, attr) -> attr.isRegularFile() && path.getFileName().toString().endsWith(".mapping"),
			FileVisitOption.FOLLOW_LINKS)) {
		stream.forEach(file -> readEnigmaFile(file, mappingAcceptor));
	} catch (UncheckedIOException e) {
		throw e.getCause();
	}
}
 
Example 4
Project: Spring-5.0-Cookbook   File: EmployeeFileStreamService.java   View Source Code Vote up 5 votes
public String searchFilesDir(String filePath, String extension) throws IOException{
	Path root = Paths.get(filePath);
	int depth = 3;
	Stream<Path> searchStream = Files.find(root, depth, (path, attr) ->
	        String.valueOf(path).endsWith(extension));
	String found = searchStream
	        .sorted()
	        .map(String::valueOf)
	        .collect(Collectors.joining(" / "));
	searchStream.close();
	return found;
}
 
Example 5
Project: centraldogma   File: Change.java   View Source Code Vote up 5 votes
/**
 * Creates a {@link List} of upsert {@link Change}s from all files under the specified directory
 * recursively.
 *
 * @param sourcePath the path to the import directory
 * @param targetPath the target directory path of the imported {@link Change}s
 *
 * @throws IOError if I/O error occurs
 */
static List<Change<?>> fromDirectory(Path sourcePath, String targetPath) {
    requireNonNull(sourcePath, "sourcePath");
    validateDirPath(targetPath, "targetPath");

    if (!Files.isDirectory(sourcePath)) {
        throw new IllegalArgumentException("sourcePath: " + sourcePath + " (must be a directory)");
    }

    final String finalTargetPath;
    if (!targetPath.endsWith("/")) {
        finalTargetPath = targetPath + '/';
    } else {
        finalTargetPath = targetPath;
    }

    try (Stream<Path> s = Files.find(sourcePath, Integer.MAX_VALUE, (p, a) -> a.isRegularFile())) {
        final int baseLength = sourcePath.toString().length() + 1;
        return s.map(sourceFilePath -> {
            final String targetFilePath =
                    finalTargetPath +
                    sourceFilePath.toString().substring(baseLength).replace(File.separatorChar, '/');

            return fromFile(sourceFilePath, targetFilePath);
        }).collect(Collectors.toList());
    } catch (IOException e) {
        throw new IOError(e);
    }
}
 
Example 6
Project: hippo   File: GenerateNesstarImportContentTask.java   View Source Code Vote up 5 votes
/**
 * @return XML files representing individual data sets (XML files under named following pattern P00000.xml)
 */
private Stream<Path> findDataSetFiles(final Path publishingPackagesDir) {
    try {
        return Files.find(
            publishingPackagesDir,
            Integer.MAX_VALUE,
            (path, basicFileAttributes) -> basicFileAttributes.isRegularFile()
                && path.getFileName().toString().matches("P\\d+.xml")
        );

    } catch (final IOException e) {
        throw new UncheckedIOException("Failed to find codeBook files.", e);
    }
}
 
Example 7
Project: VoxelScript   File: ScriptManager.java   View Source Code Vote up 5 votes
public static void updateUserScripts() {
    if (!Files.exists(user_path) || !Files.isDirectory(user_path)) {
        return;
    }
    try (Stream<Path> user_scripts = Files.find(user_path, 1, (f, attr) -> {
        return f.toAbsolutePath().toString().endsWith(".fmoka") && Files.isRegularFile(f);
    })) {
        for (Iterator<Path> it = user_scripts.iterator(); it.hasNext();) {
            Path p = it.next();
            String id = p.toFile().getName();
            id = id.substring(0, id.length() - 6);
            Script scr = get(id);
            long last_time = Files.getLastModifiedTime(p).toMillis();
            if (scr == null) {
                scr = new Script(id, p);
                scr.setLastTime(last_time);
                load(scr);
            } else {
                if (scr.getLastTime() < last_time) {
                    if (scr.getStatus() == Status.LOADED) {
                        scr.setStatus(Status.UPDATED);
                    }
                    if (scr.getStatus() == Status.ERRORED) {
                        scr.setStatus(Status.UNLOADED);
                    }
                    scr.setLastTime(last_time);
                }
            }
        }
    } catch (IOException e) {
        System.out.println("Error updating user scripts");
        e.printStackTrace();
    }
}
 
Example 8
Project: jdk8u-jdk   File: StreamTest.java   View Source Code Vote up 5 votes
public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
        assertEquals(pred.visited(), all);
        assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> fail("Expect empty stream"));
        assertEquals(pred.visited(), all);
    }
}
 
Example 9
Project: cakes   File: StreamCreateDemo.java   View Source Code Vote up 5 votes
/**
 * java.nio.file.Files 提供的几种创建文件,路径流,部分参数传null
 */
@Test
public void testStreamCreateByFiles() throws IOException {
    Stream<String> lines = Files.lines(Paths.get(""));
    Stream<Path> pathStream = Files.find(Paths.get(""), 10, null, null);
    Stream<Path> walk = Files.walk(null, null);
}
 
Example 10
Project: openjdk-jdk10   File: GenModuleInfo.java   View Source Code Vote up 5 votes
private Set<String> packages(Path dir) {
    try (Stream<Path> stream = Files.find(dir, Integer.MAX_VALUE,
                         ((path, attrs) -> attrs.isRegularFile() &&
                                           path.toString().endsWith(".class")))) {
        return stream.map(path -> toPackageName(dir.relativize(path)))
                     .filter(pkg -> pkg.length() > 0)   // module-info
                     .distinct()
                     .collect(Collectors.toSet());
    } catch (IOException x) {
        throw new UncheckedIOException(x);
    }
}
 
Example 11
Project: openjdk-jdk10   File: StreamTest.java   View Source Code Vote up 5 votes
public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
        assertEquals(pred.visited(), all);
        assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> fail("Expect empty stream"));
        assertEquals(pred.visited(), all);
    }
}
 
Example 12
Project: bazel-tools   File: Main.java   View Source Code Vote up 4 votes
private static Stream<Path> findFilesMatching(final Path directory, final String syntaxAndPattern)
    throws IOException {
  final PathMatcher matcher = directory.getFileSystem().getPathMatcher(syntaxAndPattern);
  return Files.find(
      directory, Integer.MAX_VALUE, (p, a) -> matcher.matches(p) && !a.isDirectory());
}
 
Example 13
Project: openjdk-jdk10   File: GenModuleInfo.java   View Source Code Vote up 4 votes
/**
 * Create JAR files with no module-info.class
 */
public static List<Path> createJARFiles(Path mods, Path libs) throws IOException {
    Files.createDirectory(libs);

    for (String mn : MODULES) {
        Path root = mods.resolve(mn);
        Path msrc = SRC_DIR.resolve(mn);
        Path metaInf = msrc.resolve("META-INF");
        if (Files.exists(metaInf)) {
            try (Stream<Path> resources = Files.find(metaInf, Integer.MAX_VALUE,
                    (p, attr) -> { return attr.isRegularFile();})) {
                resources.forEach(file -> {
                    try {
                        Path path = msrc.relativize(file);
                        Files.createDirectories(root.resolve(path).getParent());
                        Files.copy(file, root.resolve(path));
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                });
            }
        }
        // copy all entries except module-info.class
        try (Stream<Path> stream = Files.find(root, Integer.MAX_VALUE,
                (p, attr) -> { return attr.isRegularFile();})) {
            Stream<Path> entries = stream.filter(f -> {
                String fn = f.getFileName().toString();
                if (fn.endsWith(".class")) {
                    return !fn.equals("module-info.class");
                } else {
                    return true;
                }
            });

            JdepsUtil.createJar(libs.resolve(mn + ".jar"), root, entries);
        }
    }

   return MODULES.stream()
            .map(mn -> LIBS_DIR.resolve(mn + ".jar"))
            .collect(Collectors.toList());
}