/** * Because we're running with a security manager (most likely), we need to scan for Lingo3G * license in ES configuration directories. */ private Path scanForLingo3GLicense(Environment environment, Path pluginConfigPath) { List<Path> licenses = new ArrayList<>(); for (Path candidate : new Path[] { pluginConfigPath.resolve("license.xml"), pluginConfigPath.resolve(".license.xml"), environment.configFile().resolve("license.xml"), environment.configFile().resolve(".license.xml") }) { logger.debug( "Lingo3G license location scan: {} {}.", candidate.toAbsolutePath().normalize(), Files.isRegularFile(candidate) ? "(found)" : "(not found)"); if (Files.isRegularFile(candidate)) { licenses.add(candidate); } } if (licenses.size() > 1) { throw new ElasticsearchException( "There should be exactly one Lingo3G license on scan paths: {}", licenses); } if (licenses.size() == 1) { return licenses.iterator().next(); } else { return null; } }
/** * Execute a single filesystem test against the given path. * * @param path The {@code Path} to test * @param test The character code of the test to perform. * @return {@code null} if the test passes, or a {@code FileSystemTestFailure} if it fails. */ protected static FileSystemTestFailure testPath(final Path path, char test) { switch (test) { case 'e': return (Files.exists(path)) ? null : new FileSystemTestFailure(path, test, "The path does not exist"); case 'f': return (Files.isRegularFile(path)) ? null : new FileSystemTestFailure(path, test, "The path is not a file"); case 'd': return (Files.isDirectory(path)) ? null : new FileSystemTestFailure(path, test, "The path is not a directory"); case 'z': try { if (!Files.isRegularFile(path)) return new FileSystemTestFailure(path, test, "The path is not a file"); return (Files.size(path) < 1) ? null : new FileSystemTestFailure(path, test, "The path is not zero length"); } catch (IOException ioe) { return new FileSystemTestFailure(path, test, "The path could not be read"); } case 's': try { if (!Files.isRegularFile(path)) return new FileSystemTestFailure(path, test, "The path is not a file"); return (Files.size(path) > 0) ? null : new FileSystemTestFailure(path, test, "The path is a zero length file"); } catch (IOException ioe) { return new FileSystemTestFailure(path, test, "The path could not be read"); } case 'r': return (Files.isReadable(path)) ? null : new FileSystemTestFailure(path, test, "The path is not readable"); case 'w': return (Files.isWritable(path)) ? null : new FileSystemTestFailure(path, test, "The path is not writable"); case 'x': return (Files.isExecutable(path)) ? null : new FileSystemTestFailure(path, test, "The path is not executable"); default: throw new IllegalArgumentException("Unrecognized path test: " + test); } }
private static Stream<String> apps() { if (cl instanceof URLClassLoader) { URLClassLoader ucl = (URLClassLoader) cl; return Stream.of(ucl.getURLs()) .map(propagating(url -> Paths.get(url.toURI()))) .flatMap( propagating( path -> { if (Files.isRegularFile(path)) { return zipContents(path); } else if (Files.isDirectory(path)) { return Files.walk(path) .map(subpath -> path.relativize(subpath)) .map(subpath -> subpath.toString()) .filter(subpath -> subpath.endsWith(".class")) .map(Scanner::toClassName); } else { return Stream.empty(); } })) .filter(x -> !x.startsWith("com.cakemanny.app.")) .filter(implementsInterface(App.class)); } else { return Stream.empty(); } }
public void testPlatformBinPermissions() throws Exception { assumeTrue("posix filesystem", isPosix); Tuple<Path, Environment> env = createEnv(fs, temp); Path pluginDir = createPluginDir(temp); Path platformDir = pluginDir.resolve("platform"); Path platformNameDir = platformDir.resolve("linux-x86_64"); Path platformBinDir = platformNameDir.resolve("bin"); Files.createDirectories(platformBinDir); Path programFile = Files.createFile(platformBinDir.resolve("someprogram")); // a file created with Files.createFile() should not have execute permissions Set<PosixFilePermission> sourcePerms = Files.getPosixFilePermissions(programFile); assertFalse(sourcePerms.contains(PosixFilePermission.OWNER_EXECUTE)); assertFalse(sourcePerms.contains(PosixFilePermission.GROUP_EXECUTE)); assertFalse(sourcePerms.contains(PosixFilePermission.OTHERS_EXECUTE)); String pluginZip = createPlugin("fake", pluginDir); installPlugin(pluginZip, env.v1()); assertPlugin("fake", pluginDir, env.v2()); // check that the installed program has execute permissions, even though the one added to the // plugin didn't Path installedPlatformBinDir = env.v2() .pluginsFile() .resolve("fake") .resolve("platform") .resolve("linux-x86_64") .resolve("bin"); assertTrue(Files.isDirectory(installedPlatformBinDir)); Path installedProgramFile = installedPlatformBinDir.resolve("someprogram"); assertTrue(Files.isRegularFile(installedProgramFile)); Set<PosixFilePermission> installedPerms = Files.getPosixFilePermissions(installedProgramFile); assertTrue(installedPerms.contains(PosixFilePermission.OWNER_EXECUTE)); assertTrue(installedPerms.contains(PosixFilePermission.GROUP_EXECUTE)); assertTrue(installedPerms.contains(PosixFilePermission.OTHERS_EXECUTE)); }
public long getFileSize(Path pathRelativeToProjectRoot) throws IOException { Path path = getPathForRelativePath(pathRelativeToProjectRoot); if (!Files.isRegularFile(path)) { throw new IOException("Cannot get size of " + path + " because it is not an ordinary file."); } return Files.size(path); }
@Test public void testScanOSGiLog() throws IOException { StringBundler sb = new StringBundler(); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(System.getProperty("osgi.state.dir")), "*.log")) { for (Path path : directoryStream) { if (!Files.isRegularFile(path)) { continue; } sb.append("\nPortal log assert failure, OSGi log found: "); sb.append(path); sb.append(StringPool.COLON); sb.append(StringPool.NEW_LINE); sb.append(new String(Files.readAllBytes(path), Charset.defaultCharset())); sb.append(StringPool.NEW_LINE); } } if (sb.index() != 0) { Assert.fail(sb.toString()); } }
/** * Berechnet initial einen Hashwert über alle Dateien innerhalb des überwachten Ordners und * speichert diesen in der Datenbank. Ist der Eintrag vorhanden, so wird nur der Hashwert und das * Datum geupdated, ansonsten ein neuer Eintrag angelegt * * @param path * @param importance */ public Folder(Path path, Controller.Importance importance) { this.path = path; this.importance = importance; fileList(path.toString()); for (Path p : files) { try { // Hashwert berechnen und überprüfen ob Datei bereits // in Datenbank ist pstmt = connect.prepareStatement("SELECT * FROM hashwerte WHERE File LIKE '" + p + "';"); rs = pstmt.executeQuery(); if (Files.isRegularFile(p) == true) { if (!rs.next()) { insertInto(p, importance); } else { update(p, importance); } } } catch (Exception ex) { Logger.getLogger(Folder.class.getName()).log(Level.SEVERE, null, ex); } try { rs.close(); pstmt.close(); } catch (SQLException ex) { Logger.getLogger(Folder.class.getName()).log(Level.SEVERE, null, ex); } } }
private void initConfig() { if (Files.isRegularFile(Config.getConfigFile())) { try { config = Config.load(Config.getConfigFile()); } catch (IOException e) { logger.error("Failed to load config", e); config = new Config(); } } else { config = new Config(); } if (!config.getDefaultModSelection().hasModule(TerasologyConstants.CORE_GAMEPLAY_MODULE)) { config.getDefaultModSelection().addModule(TerasologyConstants.CORE_GAMEPLAY_MODULE); } if (!validateServerIdentity()) { CertificateGenerator generator = new CertificateGenerator(); CertificatePair serverIdentity = generator.generateSelfSigned(); config .getSecurity() .setServerCredentials(serverIdentity.getPublicCert(), serverIdentity.getPrivateCert()); config.save(); } renderingConfig = config.getRendering(); logger.info("Video Settings: " + renderingConfig.toString()); CoreRegistry.putPermanently(Config.class, config); }
public static Collection<ProfileDef> getAvailableProfiles(Path rootDir) { Path profileDir = getProfileDirectory(rootDir); if (!Files.isDirectory(profileDir)) { return Collections.emptySet(); } List<ProfileDef> result = new LinkedList<>(); try (DirectoryStream<Path> profileDirContent = Files.newDirectoryStream(profileDir)) { int suffixLength = PROFILE_FILE_NAME_SUFFIX.length(); for (Path file : profileDirContent) { if (!Files.isRegularFile(file)) { continue; } String fileName = file.getFileName().toString(); String normFileName = fileName.toLowerCase(Locale.ROOT); if (!normFileName.endsWith(PROFILE_FILE_NAME_SUFFIX)) { continue; } // This should hold, but check it just in case I don't know // something about weird case issues. if (fileName.length() >= suffixLength) { String profileName = fileName.substring(0, fileName.length() - suffixLength); result.add(new ProfileDef(null, fileName, profileName)); } } } catch (IOException ex) { LOGGER.log(Level.INFO, "Cannot list profile directory: " + profileDir, ex); } return result; }
public PathContentProvider(Path filePath, int bufferSize) throws IOException { if (!Files.isRegularFile(filePath)) throw new NoSuchFileException(filePath.toString()); if (!Files.isReadable(filePath)) throw new AccessDeniedException(filePath.toString()); this.filePath = filePath; this.fileSize = Files.size(filePath); this.bufferSize = bufferSize; }
/** Must be called or paths will not generate */ public static void initialize() { // By default, the path should be the code location (where JVE.jar is) getInstance(); try { URL urlToSource = PathManager.class.getProtectionDomain().getCodeSource().getLocation(); codeLocation = Paths.get(urlToSource.toURI()); // System.out.println("codeLocation: " + codeLocation); if (Files.isRegularFile(codeLocation)) { location = codeLocation.getParent().getParent(); // System.out.println("Running from a file (jar). Setting installPath to: " + // installPath); } } catch (URISyntaxException e) { // Can't use logger, because logger not set up when PathManager is used. // System.out.println("Failed to convert code location to uri"); } // If terasology.jar's location could not be resolved (maybe running from an IDE) then fallback // on working path if (location == null) { location = Paths.get("").toAbsolutePath(); // System.out.println("installPath was null, running from IDE. Setting it to: " + // installPath); } logger = LoggerFactory.getLogger(PathManager.class); logger.info("Location: " + getLocationPath() + "/"); }
public static void main(String[] args) { try { File[] files = new File(Paths.get("/Users/AriApar/Dropbox", "results").toString()) .listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return (name.contains("2x") || name.contains("3x") || name.contains("4x") || name.contains("5x") || name.contains("6x") || name.contains("7x") || name.contains("8x")); } }); for (File f : files) { Path filePath = f.toPath(); File resFile = new File( Paths.get("/Users/AriApar/Documents", "lazy_wo_cost", "results", f.getName()) .toString()); if (Files.isRegularFile(filePath) && resFile.exists() && !resFile.isDirectory()) { if (!matchesWinners(f, resFile)) System.out.println("Winners for " + f.getName() + " doesn't match"); } } } catch (Exception e) { e.printStackTrace(); } }
public int run() throws IOException { try { int b = in.read(); if (b != -1) { dOut.write(b); size++; return 1; } else { dOut.close(); tmpOut.close(); LongObjectId loid = LongObjectId.fromRaw(dOut.getMessageDigest().digest()); Path mediaFile = lfsUtil.getMediaFile(loid); if (Files.isRegularFile(mediaFile)) { long fsSize = Files.size(mediaFile); if (fsSize != size) { throw new CorruptMediaFile(mediaFile, size, fsSize); } } else { FileUtils.mkdirs(mediaFile.getParent().toFile(), true); FileUtils.rename(tmpFile.toFile(), mediaFile.toFile()); } LfsPointer lfsPointer = new LfsPointer(loid, size); lfsPointer.encode(out); out.close(); return -1; } } catch (IOException e) { out.close(); dOut.close(); tmpOut.close(); throw e; } }
@GET @javax.ws.rs.Path("/overview") @NoCache public Response getAtonOverviewIcon(@Context HttpServletRequest request) throws Exception { long t0 = System.currentTimeMillis(); String type = request.getParameter("seamark:type"); if (StringUtils.isBlank(type)) { return Response.temporaryRedirect(new URI("/img/aton/aton.png")).build(); } // Prepare an AtoN to use as a template for icon construction AtonNode aton = new AtonNode(); // Construct a repository path to the icon Path path = repositoryService.getRepoRoot().resolve(OVERVIEW_ICON_REPO); path = addParam(aton, path, request, "seamark:type"); path = addParam(aton, path, request, "seamark:" + type + ":category"); path = addParam(aton, path, request, "seamark:" + type + ":shape"); path = addParam(aton, path, request, "seamark:" + type + ":colour"); path = addParam(aton, path, request, "seamark:" + type + ":colour_pattern"); path = addParam(aton, path, request, "seamark:topmark:shape"); path = addParam(aton, path, request, "seamark:topmark:colour"); path = addParam(aton, path, request, "seamark:light:character"); path = addParam(aton, path, request, "seamark:light:colour"); // And the actual icon file path = path.resolve("aton_icon_" + OVERVIEW_ICON_WIDTH + "x" + OVERVIEW_ICON_HEIGHT + ".png"); if (!Files.isRegularFile(path)) { checkCreateParentDirs(path); try (FileOutputStream out = new FileOutputStream(path.toFile())) { AtonIconRenderer.renderIcon( aton.toVo(), "png", out, OVERVIEW_ICON_WIDTH, // width OVERVIEW_ICON_HEIGHT, // height OVERVIEW_ICON_WIDTH / 3, // x 2 * OVERVIEW_ICON_HEIGHT / 3, // y OVERVIEW_ICON_SCALE // scale ); log.trace( "Generated AtoN PNG " + path + " in " + (System.currentTimeMillis() - t0) + " ms"); } } // Redirect to the icon String iconUri = repositoryService.getRepoUri(path); return Response.temporaryRedirect(new URI("../" + iconUri)).build(); }
public static Config createDefaultConfig( Path root, ImmutableMap<String, ImmutableMap<String, String>> configOverrides) throws IOException { ImmutableList.Builder<Path> configFileBuilder = ImmutableList.builder(); configFileBuilder.addAll(listFiles(GLOBAL_BUCK_CONFIG_DIRECTORY_PATH)); if (Files.isRegularFile(GLOBAL_BUCK_CONFIG_FILE_PATH)) { configFileBuilder.add(GLOBAL_BUCK_CONFIG_FILE_PATH); } Path homeDirectory = Paths.get(System.getProperty("user.home")); Path userConfigDir = homeDirectory.resolve(DEFAULT_BUCK_CONFIG_DIRECTORY_NAME); configFileBuilder.addAll(listFiles(userConfigDir)); Path userConfigFile = homeDirectory.resolve(DEFAULT_BUCK_CONFIG_FILE_NAME); if (Files.isRegularFile(userConfigFile)) { configFileBuilder.add(userConfigFile); } Path configFile = root.resolve(DEFAULT_BUCK_CONFIG_FILE_NAME); if (Files.isRegularFile(configFile)) { configFileBuilder.add(configFile); } Path overrideConfigFile = root.resolve(DEFAULT_BUCK_CONFIG_OVERRIDE_FILE_NAME); if (Files.isRegularFile(overrideConfigFile)) { configFileBuilder.add(overrideConfigFile); } ImmutableList<Path> configFiles = configFileBuilder.build(); ImmutableList.Builder<ImmutableMap<String, ImmutableMap<String, String>>> builder = ImmutableList.builder(); for (Path file : configFiles) { try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { ImmutableMap<String, ImmutableMap<String, String>> parsedConfiguration = Inis.read(reader); LOG.debug("Loaded a configuration file %s: %s", file, parsedConfiguration); builder.add(parsedConfiguration); } } LOG.debug("Adding configuration overrides: %s", configOverrides); builder.add(configOverrides); return new Config(builder.build()); }
/** Validate that the report pages were generated correctly */ private void validateReports(GraphContext context) { ReportService reportService = new ReportService(context); ReportModel reportModel = getMainApplicationReport(context); Path appReportPath = Paths.get(reportService.getReportDirectory(), reportModel.getReportFilename()); TestJavaApplicationOverviewUtil util = new TestJavaApplicationOverviewUtil(); util.loadPage(appReportPath); util.checkFilePathAndTag("src_example", "src/main/resources/test.properties", "Properties"); util.checkFilePathAndTag("src_example", "src/main/resources/WEB-INF/web.xml", "Web XML 3.0"); util.checkFilePathAndTag( "src_example", "src/main/resources/WEB-INF/web.xml", "TestTag2"); // WINDUP-679 util.checkFilePathAndIssues( "src_example", "org.windup.examples.servlet.SampleServlet", "References annotation 'javax.servlet.annotation.WebServlet'"); util.checkFilePathAndIssues("src_example", "src/main/resources/WEB-INF/web.xml", "Container"); util.checkFilePathAndIssues( "src_example", "src/main/resources/WEB-INF/web.xml", "Title for Hint from XML"); util.checkFilePathAndIssues( "src_example", "src/main/resources/WEB-INF/web.xml", "title from user script"); util.checkFilePathAndIssues( "src_example", "org.windup.examples.servlet.SampleServlet", "javax.servlet.http.HttpServletRequest usage"); XsltTransformationService xsltService = new XsltTransformationService(context); Assert.assertTrue( Files.isRegularFile( xsltService.getTransformedXSLTPath().resolve("web-xml-converted-example.xml"))); Assert.assertTrue( Files.isRegularFile( xsltService .getTransformedXSLTPath() .resolve("web-xmluserscript-converted-example.xml"))); validateSpringBeanReport(context); validateEJBReport(context); validateJPAReport(context); validateMigrationIssuesReport(context); }
private void onNewPath(Path path) throws IOException { if (Files.isHidden(path)) { return; } if (Files.isRegularFile(path)) { onNewFile(path); } else { onNewDirectory(path); } }
@Test public void whenBuckBuiltTwiceLogIsPresent() throws IOException, InterruptedException { AssumeAndroidPlatform.assumeSdkIsAvailable(); final ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "file_watching", tmp); workspace.setUp(); workspace.runBuckdCommand("build", "//java/com/example/activity:activity").assertSuccess(); Path buildLogFile = workspace.getPath("buck-out/bin/build.log"); assertTrue(Files.isRegularFile(buildLogFile)); Files.delete(buildLogFile); ProcessResult rebuild = workspace.runBuckdCommand("build", "//java/com/example/activity:activity"); rebuild.assertSuccess(); buildLogFile = workspace.getPath("buck-out/bin/build.log"); assertTrue(Files.isRegularFile(buildLogFile)); }
static boolean isZip(Path path) { if (!Files.isRegularFile(path)) { return false; } try (ZipFile ignored = new ZipFile(path.toFile())) { return true; } catch (IOException ignored) { // Probably not a JAR file. return false; } }
// Set type of file as name of the element private void setType(Element element, Path path) { if (Files.isDirectory(path)) { element.setLocalName(FileType.DIR.getName()); return; } else if (Files.isRegularFile(path)) { element.setLocalName(FileType.FILE.getName()); return; } else if (Files.isSymbolicLink(path)) { element.setLocalName(FileType.SYMLINK.getName()); return; } else element.setLocalName(FileType.OTHER.getName()); }
@Test public void testFullClass() throws IOException { Path path = Paths.get("src/test/java/com/carrotsearch/hppc/generator/parser/KTypeVTypeClass.java"); // Path path = // Paths.get("c:\\carrot2\\gh.carrotsearch\\hppc\\hppc\\src\\main\\templates\\com\\carrotsearch\\hppc\\KTypeArrayDeque.java"); Assume.assumeTrue(Files.isRegularFile(path)); SignatureProcessor sp = new SignatureProcessor(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); System.out.println(sp.process(new TemplateOptions(Type.LONG, Type.GENERIC))); }
private String loadApplicationKey() throws IOException { final Path configFile = Paths.get("settings.properties"); // NOI18N. assertTrue(Files.exists(configFile)); assertTrue(Files.isRegularFile(configFile)); assertTrue(Files.isReadable(configFile)); final Properties settings = new Properties(); try (final InputStream input = Files.newInputStream(configFile)) { settings.load(input); } final String appKey = settings.getProperty("app.key"); // NOI18N. assertNotNull(appKey); return appKey; }
Cache(String d) throws IOException { root = fs.getPath(d); assert Files.isDirectory(root); notesdb = root.resolve("notes.db"); assert Files.isRegularFile(notesdb) : "notes.db isn't exist"; supportSapComNotes = root.resolve("support-sap-com-notes"); if (!Files.exists(supportSapComNotes)) Files.createDirectory(supportSapComNotes); launchpad = root.resolve("launchpad"); if (!Files.exists(launchpad)) Files.createDirectory(launchpad); }
/** * Attempts to read or write data from or to a file. * * <p>If the file is found to be missing or the reset parameter is set to true, the file will be * written with the default data, and the default data will be returned. * * <p>If the file is found to be a regular, readable file, the file is read in, and its contents * returned. * * <p>If the method runs into an error while attempting any of this, a message is printed to the * log, and the default data is returned. * * @param directory the directory the file is in. * @param fileName the name of the file, without the .txt ending. * @param defaultData the data to write to the file, or default to. * @param reset if the file should be overwritten with the default data. * @return the data contained in the file, or the default data. */ public static String readOrWrite( String directory, String fileName, String defaultData, boolean reset) { Path path = Paths.get(directory, fileName + ".txt"); try { if (Files.isRegularFile(path) && !reset) { return new String(Files.readAllBytes(path)); } else { Files.write(path, defaultData.getBytes()); } } catch (IOException e) { LogHelper.info("Caught IOException when reading " + path.getFileName()); } return defaultData; }
@Test public void testUploadFile() throws FileNotFoundException { InputStream stream = new FileInputStream("/opt/digiverso/junit/data/metadata.xml"); Part file = new MockUploadedFile(stream, "./some/path\\junit.xml"); MassImportForm massImportForm = new MassImportForm(); assertNotNull(massImportForm); massImportForm.setTemplate(template); massImportForm.setUploadedFile(file); massImportForm.uploadFile(); Path dest = Paths.get(ConfigurationHelper.getInstance().getTemporaryFolder(), "junit.xml"); assertTrue(Files.exists(dest) && Files.isRegularFile(dest)); }
// Returns the backup file of the specified resource entry if available or null. // A backup file is either a *.bak file or a biffed file which has been overridden. private static Path getBackupFile(ResourceEntry entry) { Path file = getCurrentFile(entry); if (entry instanceof FileResourceEntry || (entry instanceof BIFFResourceEntry && entry.hasOverride())) { if (file != null) { Path bakFile = file.getParent().resolve(file.getFileName().toString() + ".bak"); if (Files.isRegularFile(bakFile)) { return bakFile; } } } else if (entry instanceof BIFFResourceEntry) { return file; } return null; }
private Optional<String> readFileIfItExists(Path fileToRead, String pathRelativeToProjectRoot) { if (Files.isRegularFile(fileToRead)) { String contents; try { contents = new String(Files.readAllBytes(fileToRead), Charsets.UTF_8); } catch (IOException e) { // Alternatively, we could return Optional.absent(), though something seems suspicious if we // have already verified that fileToRead is a file and then we cannot read it. throw new RuntimeException("Error reading " + pathRelativeToProjectRoot, e); } return Optional.of(contents); } else { return Optional.absent(); } }
/** * Attempts to open the file for future read access. Returns {@link Optional#absent()} if the file * does not exist. */ public Optional<Reader> getReaderIfFileExists(Path pathRelativeToProjectRoot) { Path fileToRead = getPathForRelativePath(pathRelativeToProjectRoot); if (Files.isRegularFile(fileToRead)) { try { return Optional.of( (Reader) new BufferedReader( new InputStreamReader(newFileInputStream(pathRelativeToProjectRoot)))); } catch (Exception e) { throw new RuntimeException("Error reading " + pathRelativeToProjectRoot, e); } } else { return Optional.absent(); } }
// Returns an unoccupied filename based on 'file'. private static Path getTempFile(Path file) { Path retVal = null; if (file != null && Files.isRegularFile(file)) { final String fmt = ".%03d"; Path filePath = file.getParent(); String fileName = file.getFileName().toString(); for (int i = 0; i < 1000; i++) { Path tmp = filePath.resolve(fileName + String.format(fmt, i)); if (!Files.exists(tmp) && Files.notExists(tmp)) { retVal = tmp; break; } } } return retVal; }
/** * @param root * @param visitor * @param maxDepth */ public void browse(File root, Visitor visitor, int maxDepth) { try { Files.walk(root.toPath(), maxDepth) .forEach( path -> { if (Files.isDirectory(path)) { visitor.doFolder(); } else if (Files.isRegularFile(path)) { visitor.doFile(); } else { visitor.doOther(); } }); } catch (Exception e) { e.printStackTrace(); } }