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:me.ryandowling.allmightybot.AllmightyBot.java

private void loadUserOnlineTime() {
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Utils.getUsersDir())) {
        for (Path path : directoryStream) {
            if (Files.isDirectory(path)) {
                String username = path.getFileName().toString();
                if (Files.exists(Utils.getUserLoginTimeFile(username))) {
                    Type type = new TypeToken<Map<String, Integer>>() {
                    }.getType();//from  w  ww. j  a  v  a  2  s .  c om
                    Map<String, Integer> timeInChannel = GSON.fromJson(
                            FileUtils.readFileToString(Utils.getUserLoginTimeFile(username).toFile()), type);
                    this.userOnlineTime.put(username, timeInChannel);
                }
            }
        }
    } catch (IOException ex) {
    }
}

From source file:com.cloudbees.clickstack.util.Files2.java

private static void dump(@Nonnull Path path, int depth) throws RuntimeIOException {
    try {/*  w  ww  .j av a2 s.  co  m*/
        depth++;
        String icon = Files.isDirectory(path) ? " + " : " |- ";
        System.out.println(Strings.repeat(" ", depth) + icon + path.getFileName() + "\t"
                + PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));

        if (Files.isDirectory(path)) {
            DirectoryStream<Path> children = Files.newDirectoryStream(path);
            for (Path child : children) {
                dump(child, depth);
            }
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception dumping " + path, e);
    }
}

From source file:org.wso2.carbon.apimgt.core.util.APIFileUtils.java

/**
 * Queries the list of directories available under a root directory path
 *
 * @param path full path of the root directory
 * @return Set of directory path under the root directory given by path
 * @throws APIMgtDAOException if an error occurs while listing directories
 *///w ww. j  av a  2s  . co  m
public static Set<String> getDirectoryList(String path) throws APIMgtDAOException {
    Set<String> directoryNames = new HashSet<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(path))) {
        for (Path directoryPath : directoryStream) {
            directoryNames.add(directoryPath.toString());
        }
    } catch (IOException e) {
        String errorMsg = "Error while listing directories under " + path;
        log.error(errorMsg, e);
        throw new APIMgtDAOException(errorMsg, e);
    }
    return directoryNames;
}

From source file:org.apache.reef.runtime.mesos.driver.REEFScheduler.java

private String getReefTarUri(final String jobIdentifier) {
    try {/*from  www.  j a  v a 2 s .c om*/
        // Create REEF_TAR
        final FileOutputStream fileOutputStream = new FileOutputStream(REEF_TAR);
        final TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(
                new GZIPOutputStream(fileOutputStream));
        final File globalFolder = new File(this.fileNames.getGlobalFolderPath());
        final DirectoryStream<Path> directoryStream = Files.newDirectoryStream(globalFolder.toPath());

        for (final Path path : directoryStream) {
            tarArchiveOutputStream.putArchiveEntry(
                    new TarArchiveEntry(path.toFile(), globalFolder + "/" + path.getFileName()));

            final BufferedInputStream bufferedInputStream = new BufferedInputStream(
                    new FileInputStream(path.toFile()));
            IOUtils.copy(bufferedInputStream, tarArchiveOutputStream);
            bufferedInputStream.close();

            tarArchiveOutputStream.closeArchiveEntry();
        }
        directoryStream.close();
        tarArchiveOutputStream.close();
        fileOutputStream.close();

        // Upload REEF_TAR to HDFS
        final FileSystem fileSystem = FileSystem.get(new Configuration());
        final org.apache.hadoop.fs.Path src = new org.apache.hadoop.fs.Path(REEF_TAR);
        final String reefTarUriValue = fileSystem.getUri().toString() + this.jobSubmissionDirectoryPrefix + "/"
                + jobIdentifier + "/" + REEF_TAR;
        final org.apache.hadoop.fs.Path dst = new org.apache.hadoop.fs.Path(reefTarUriValue);
        fileSystem.copyFromLocalFile(src, dst);

        return reefTarUriValue;
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.roda.core.storage.fs.FSUtils.java

/**
 * List containers/*from  w ww.  jav a 2 s.c o m*/
 * 
 * @param basePath
 *          base path
 * @throws GenericException
 */
public static CloseableIterable<Container> listContainers(final Path basePath) throws GenericException {
    CloseableIterable<Container> containerIterable;
    try {
        final DirectoryStream<Path> directoryStream = Files.newDirectoryStream(basePath);
        final Iterator<Path> pathIterator = directoryStream.iterator();
        containerIterable = new CloseableIterable<Container>() {

            @Override
            public Iterator<Container> iterator() {
                return new Iterator<Container>() {

                    @Override
                    public boolean hasNext() {
                        return pathIterator.hasNext();
                    }

                    @Override
                    public Container next() {
                        Path next = pathIterator.next();
                        Container ret;
                        try {
                            ret = convertPathToContainer(basePath, next);
                        } catch (NoSuchElementException | GenericException | RequestNotValidException e) {
                            LOGGER.error("Error while listing containers, while parsing resource " + next, e);
                            ret = null;
                        }

                        return ret;
                    }

                };
            }

            @Override
            public void close() throws IOException {
                directoryStream.close();
            }
        };

    } catch (IOException e) {
        throw new GenericException("Could not list contents of entity at: " + basePath, e);
    }

    return containerIterable;
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemImpl.java

void move(CryptoPath cleartextSource, CryptoPath cleartextTarget, CopyOption... options) throws IOException {
    if (cleartextSource.equals(cleartextTarget)) {
        return;//from   www. j av  a2 s.c  o m
    }
    Path ciphertextSourceFile = cryptoPathMapper.getCiphertextFilePath(cleartextSource,
            CiphertextFileType.FILE);
    Path ciphertextSourceDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextSource,
            CiphertextFileType.DIRECTORY);
    if (Files.exists(ciphertextSourceFile)) {
        // FILE:
        Path ciphertextTargetFile = cryptoPathMapper.getCiphertextFilePath(cleartextTarget,
                CiphertextFileType.FILE);
        Files.move(ciphertextSourceFile, ciphertextTargetFile, options);
    } else if (Files.exists(ciphertextSourceDirFile)) {
        // DIRECTORY:
        Path ciphertextTargetDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextTarget,
                CiphertextFileType.DIRECTORY);
        if (!ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING)) {
            // try to move, don't replace:
            Files.move(ciphertextSourceDirFile, ciphertextTargetDirFile, options);
        } else if (ArrayUtils.contains(options, StandardCopyOption.ATOMIC_MOVE)) {
            // replace atomically (impossible):
            assert ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING);
            throw new AtomicMoveNotSupportedException(cleartextSource.toString(), cleartextTarget.toString(),
                    "Replacing directories during move requires non-atomic status checks.");
        } else {
            // move and replace (if dir is empty):
            assert ArrayUtils.contains(options, StandardCopyOption.REPLACE_EXISTING);
            assert !ArrayUtils.contains(options, StandardCopyOption.ATOMIC_MOVE);
            if (Files.exists(ciphertextTargetDirFile)) {
                Path ciphertextTargetDir = cryptoPathMapper.getCiphertextDirPath(cleartextTarget);
                try (DirectoryStream<Path> ds = Files.newDirectoryStream(ciphertextTargetDir)) {
                    if (ds.iterator().hasNext()) {
                        throw new DirectoryNotEmptyException(cleartextTarget.toString());
                    }
                }
                Files.delete(ciphertextTargetDir);
            }
            Files.move(ciphertextSourceDirFile, ciphertextTargetDirFile, options);
        }
        dirIdProvider.move(ciphertextSourceDirFile, ciphertextTargetDirFile);
    } else {
        throw new NoSuchFileException(cleartextSource.toString());
    }
}

From source file:org.corehunter.tests.data.simple.SimpleDefaultGenotypeDataTest.java

@Test
public void diploidErroneousFiles() throws IOException {
    System.out.println(" |- Test diploid erroneous files:");
    Path dir = Paths.get(SimpleDefaultGenotypeDataTest.class.getResource(ERRONEOUS_FILES_DIR).getPath());
    try (DirectoryStream<Path> directory = Files.newDirectoryStream(dir)) {
        for (Path file : directory) {
            System.out.print("  |- " + file.getFileName().toString() + ": ");
            FileType type = file.toString().endsWith(".txt") ? FileType.TXT : FileType.CSV;
            boolean thrown = false;
            try {
                SimpleDefaultGenotypeData.readData(file, type);
            } catch (IOException ex) {
                thrown = true;/*from ww w.j  av a2 s . co m*/
                System.out.print(ex.getMessage());
            } finally {
                System.out.println();
            }
            assertTrue("File " + file + " should throw exception.", thrown);
        }
    }
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

private static void getFiles(Path dir, String path, SortedSet<FileInfo> res) {
    if (!Files.exists(dir)) {
        return;/*www  .jav a  2  s  .c  o m*/
    }
    assert (Files.isDirectory(dir));
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir)) {
        for (Path p : ds) {
            if (Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)) {
                getFiles(p, path + "/" + p.getFileName(), res);
            } else if (!p.getFileName().toString().endsWith(".mimetype")) {
                res.add(new FileInfo(path, p.getFileName().toString()));
            }
        }
    } catch (IOException e) {
        FilebasedRepository.logger.debug("Cannot close ds", e);
    }
}

From source file:org.niord.core.batch.BatchService.java

/** Returns the named sub-folders **/
private List<Path> getBatchJobSubFolders(String subFolderName) {
    List<Path> subFolders = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(batchJobRoot)) {
        stream.forEach(p -> {//  w w  w  .j  a  va 2 s.  c o  m
            Path executionFolder = p.resolve(subFolderName);
            if (Files.isDirectory(executionFolder)) {
                subFolders.add(executionFolder);
            }
        });
    } catch (IOException e) {
        log.debug("Failed finding '" + subFolderName + "' batch job folders: " + e);
    }
    return subFolders;
}

From source file:org.niord.core.batch.BatchService.java

/** Returns the list of regular files in the given directory **/
private List<Path> getDirectoryFiles(Path dir) {
    List<Path> files = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path p : stream) {
            if (Files.isReadable(p) && Files.isRegularFile(p) && !Files.isHidden(p)) {
                files.add(p);//from   w  w w . j  a va  2  s . com
            }
        }
    } catch (IOException ignored) {
    }
    return files;
}