Example usage for java.nio.file Files newDirectoryStream

List of usage examples for java.nio.file Files newDirectoryStream

Introduction

In this page you can find the example usage for java.nio.file Files newDirectoryStream.

Prototype

public static DirectoryStream<Path> newDirectoryStream(Path dir) throws IOException 

Source Link

Document

Opens a directory, returning a DirectoryStream to iterate over all entries in the directory.

Usage

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Cleans the Workspace of the AUT and creates a demo Project.
 * //w ww .  j ava2 s  . c  om
 * @throws IOException
 *             on reset the workspace.
 * @throws URISyntaxException
 *             on reset the workspace.
 */
private void prepareAUTWorkspace() throws IOException, URISyntaxException {

    File wsPathFile = new File(getWorkspacePath());
    Path wsPath = wsPathFile.toPath();
    if (wsPathFile.exists()) {
        Files.walkFileTree(wsPath, getDeleteFileVisitor());
        LOGGER.info("Removed AUT_WS: " + getWorkspacePath());
    }
    Files.createDirectory(wsPath);
    Map<String, String> env = new HashMap<String, String>();
    env.put("create", "true");
    FileSystem fs = FileSystems.newFileSystem(getClass().getResource("/DemoWebTests.zip").toURI(), env);
    Iterable<Path> rootDirectories = fs.getRootDirectories();
    for (Path root : rootDirectories) {
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(root);
        for (Path path : directoryStream) {
            if (path.getFileName().startsWith("DemoWebTests.zip")) {
                LOGGER.info("Found DemoWebTest.");
                Files.copy(path, Paths.get(wsPath.toString(), "DemoWebTests.zip"));
                URI uriDemoZip = new URI("jar:" + Paths.get(wsPath.toString(), "/DemoWebTests.zip").toUri());
                LOGGER.info(uriDemoZip);
                FileSystem zipFs = FileSystems.newFileSystem(uriDemoZip, env);
                copyFolder(zipFs.getPath("/"), Paths.get(getWorkspacePath()));
                zipFs.close();
            }
        }
    }
    fs.close();
    LOGGER.info("Created Demoproject in: " + getWorkspacePath());
}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * copies the directories./*from   w  w w . j a  v  a2 s.c  o  m*/
 * 
 * @param src
 *            source-directory
 * @param dest
 *            destination-directory
 * @throws IOException
 *             IOException
 */
private void copyFolder(Path src, Path dest) throws IOException {
    if (Files.isDirectory(src)) {
        // if directory not exists, create it
        if (!Files.exists(dest)) {
            Files.createDirectory(dest);
        }
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(src);
        for (Path path : directoryStream) {
            Path srcFile = path;
            Path destFile = Paths.get(dest.toString() + "/" + path.getFileName());
            copyFolder(srcFile, destFile);
        }
    } else {
        Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
    }
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * Deletes old backup files in backup folder; keep only last X files
 * /*from  www.j a v a 2s  .c om*/
 * @param file
 *          the file of backup to be deleted
 * @param keep
 *          keep last X versions
 */
public static final void deleteOldBackupFile(Path file, int keep) {
    ArrayList<Path> al = new ArrayList<>();
    String fname = file.getFileName().toString();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get("backup"))) {
        for (Path path : directoryStream) {
            if (path.getFileName().toString().matches(fname + "\\.\\d{4}\\-\\d{2}\\-\\d{2}\\.zip") || // name.ext.yyyy-mm-dd.zip
                    path.getFileName().toString().matches(fname + "\\.\\d{4}\\-\\d{2}\\-\\d{2}")) { // old name.ext.yyyy-mm-dd
                al.add(path);
            }
        }
    } catch (IOException ex) {
    }

    for (int i = 0; i < al.size() - keep; i++) {
        // System.out.println("del " + al.get(i).getName());
        deleteFileSafely(al.get(i));
    }

}

From source file:org.tinymediamanager.core.movie.tasks.MovieUpdateDatasourceTask2.java

/**
 * simple NIO File.listFiles() replacement<br>
 * returns ONLY regular files (NO folders, NO hidden) in specified dir, filtering against our badwords (NOT recursive)
 * /*from  ww  w.j av  a2s.  co m*/
 * @param directory
 *          the folder to list the files for
 * @return list of files&folders
 */
public static List<Path> listFilesOnly(Path directory) {
    List<Path> fileNames = new ArrayList<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        for (Path path : directoryStream) {
            if (Utils.isRegularFile(path)) {
                String fn = path.getFileName().toString().toUpperCase(Locale.ROOT);
                if (!skipFolders.contains(fn) && !fn.matches(skipRegex) && !MovieModuleManager.MOVIE_SETTINGS
                        .getMovieSkipFolders().contains(path.toFile().getAbsolutePath())) {
                    fileNames.add(path.toAbsolutePath());
                } else {
                    LOGGER.debug("Skipping: " + path);
                }
            }
        }
    } catch (IOException ex) {
    }
    return fileNames;
}

From source file:org.tinymediamanager.core.movie.tasks.MovieUpdateDatasourceTask2.java

/**
 * simple NIO File.listFiles() replacement<br>
 * returns all files & folders in specified dir, filtering against our skip folders (NOT recursive)
 * /*from  w  ww . ja v  a 2  s. c o m*/
 * @param directory
 *          the folder to list the items for
 * @return list of files&folders
 */
public static List<Path> listFilesAndDirs(Path directory) {
    List<Path> fileNames = new ArrayList<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        for (Path path : directoryStream) {
            String fn = path.getFileName().toString().toUpperCase(Locale.ROOT);
            if (!skipFolders.contains(fn) && !fn.matches(skipRegex) && !MovieModuleManager.MOVIE_SETTINGS
                    .getMovieSkipFolders().contains(path.toFile().getAbsolutePath())) {
                fileNames.add(path.toAbsolutePath());
            } else {
                LOGGER.debug("Skipping: " + path);
            }
        }
    } catch (IOException ex) {
    }
    return fileNames;
}

From source file:org.apache.storm.localizer.AsyncLocalizer.java

private void forEachTopologyDistDir(ConsumePathAndId consumer) throws IOException {
    Path stormCodeRoot = Paths.get(ConfigUtils.supervisorStormDistRoot(conf));
    if (Files.exists(stormCodeRoot) && Files.isDirectory(stormCodeRoot)) {
        try (DirectoryStream<Path> children = Files.newDirectoryStream(stormCodeRoot)) {
            for (Path child : children) {
                if (Files.isDirectory(child)) {
                    String topologyId = child.getFileName().toString();
                    consumer.accept(child, topologyId);
                }//  w  w w. ja  v a2s .  c  om
            }
        }
    }
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * extract our templates (use force to overwrite)
 *///from  ww  w.j a  va2s  . co  m
public static final void extractTemplates(boolean force) {
    Path dest = Paths.get("templates");
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dest)) {
        for (Path path : directoryStream) {
            if (!Files.isDirectory(path)) {
                String fn = path.getFileName().toString();
                if (fn.endsWith(".jar")) {
                    // always extract when dir not existing
                    if (!Files.exists(dest.resolve(Paths.get(fn.replace(".jar", ""))))) {
                        Utils.unzip(path, dest);
                    } else {
                        if (force) {
                            Utils.unzip(path, dest);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        LOGGER.warn("failed to extract templates: " + e.getMessage());
    }
}

From source file:org.roda.core.model.ModelService.java

public synchronized void findOldLogsAndMoveThemToStorage(Path logDirectory, Path currentLogFile)
        throws RequestNotValidException, AuthorizationDeniedException, NotFoundException {
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(logDirectory)) {

        for (Path path : directoryStream) {
            if (!path.equals(currentLogFile)) {
                try {
                    StoragePath logPath = ModelUtils.getLogStoragePath(path.getFileName().toString());
                    storage.createBinary(logPath, new FSPathContentPayload(path), false);
                    Files.delete(path);
                } catch (IOException | GenericException | AlreadyExistsException e) {
                    LOGGER.error("Error archiving log file", e);
                }/*from ww w .  ja v a 2s  .c o m*/
            }
        }
    } catch (IOException e) {
        LOGGER.error("Error listing directory for log files", e);
    }
}

From source file:com.epam.catgenome.manager.FileManager.java

/**
 * Returns contents of a directory, specified by path, to browse NGS files
 *
 * @param path a path to directory to browse
 * @return {@link List} of {@link FsDirectory}s, and {@link FsFile}, representing subdirectories and files
 * @throws IOException/*from  w w  w .  j  a  v a2  s  . c  o m*/
 */
public List<AbstractFsItem> loadDirectoryContents(String path) throws IOException {
    if (!filesBrowsingAllowed) {
        throw new AccessDeniedException("Server file system browsing is not allowed");
    }

    List<File> parentDirs = new ArrayList<>();
    if (path == null) {
        if ("/".equals(ngsDataRootPath)) {
            parentDirs = Arrays.asList(File.listRoots());
        } else {
            parentDirs.add(new File(ngsDataRootPath));
        }
    } else {
        parentDirs.add(new File(path));
    }

    Assert.isTrue(parentDirs.stream().allMatch(File::exists), "Specified path does not exist: " + path);
    Assert.isTrue(parentDirs.stream().allMatch(File::isDirectory),
            "Specified path is not a directory: " + path);

    List<AbstractFsItem> items = new ArrayList<>();

    boolean accessDenied = false;
    String fileName = "";
    String otherFileName = "";

    for (File parentDir : parentDirs) {
        if (parentDir.listFiles() == null) {
            continue;
        }

        try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(parentDir.toPath())) {
            for (Path child : dirStream) {
                try {
                    File childFile = child.toFile();
                    if (childFile.isDirectory()) {
                        FsDirectory directory = new FsDirectory();
                        directory.setPath(childFile.getAbsolutePath());
                        if (childFile.canRead()) {
                            directory.setFileCount(countChildrenFiles(child));
                        }

                        items.add(directory);
                    } else {
                        addFsFile(items, childFile);
                    }
                } catch (AccessDeniedException e) {
                    LOGGER.error("Access denied:", e);
                    accessDenied = true;
                    fileName = e.getFile();
                    otherFileName = e.getOtherFile();
                }
            }

            if (items.isEmpty() && accessDenied) {
                throw new AccessDeniedException(fileName, otherFileName, "Access denied");
            }
        }
    }

    return items;
}

From source file:org.elasticsearch.test.ElasticsearchIntegrationTest.java

/**
 * Asserts that there are no files in the specified path
 *///from w w  w. j av a2  s  . co  m
public void assertPathHasBeenCleared(Path path) throws Exception {
    logger.info("--> checking that [{}] has been cleared", path);
    int count = 0;
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    if (Files.exists(path)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
            for (Path file : stream) {
                logger.info("--> found file: [{}]", file.toAbsolutePath().toString());
                if (Files.isDirectory(file)) {
                    assertPathHasBeenCleared(file);
                } else if (Files.isRegularFile(file)) {
                    count++;
                    sb.append(file.toAbsolutePath().toString());
                    sb.append("\n");
                }
            }
        }
    }
    sb.append("]");
    assertThat(count + " files exist that should have been cleaned:\n" + sb.toString(), count, equalTo(0));
}