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.freeeed.main.ActionStaging.java

private long dirSize(Path path) {
    long size = 0;
    try {/*from  w  w w  .  j av a 2s  .  co  m*/
        DirectoryStream ds = Files.newDirectoryStream(path);
        for (Object o : ds) {
            Path p = (Path) o;
            if (Files.isDirectory(p)) {
                size += dirSize(p);
            } else {
                size += Files.size(p);
            }
        }
    } catch (IOException e) {
        LOGGER.error("Dir size calculation error", e);
    }
    return size;
}

From source file:com.buaa.cfs.utils.IOUtils.java

/**
 * Return the complete list of files in a directory as strings.<p/>
 * <p>/*from w  ww .  j av a 2  s. c  o m*/
 * This is better than File#listDir because it does not ignore IOExceptions.
 *
 * @param dir    The directory to list.
 * @param filter If non-null, the filter to use when listing this directory.
 *
 * @return The list of files in the directory.
 *
 * @throws IOException On I/O error
 */
public static List<String> listDirectory(File dir, FilenameFilter filter) throws IOException {
    ArrayList<String> list = new ArrayList<String>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir.toPath())) {
        for (Path entry : stream) {
            String fileName = entry.getFileName().toString();
            if ((filter == null) || filter.accept(dir, fileName)) {
                list.add(fileName);
            }
        }
    } catch (DirectoryIteratorException e) {
        throw e.getCause();
    }
    return list;
}

From source file:au.org.ands.vocabs.toolkit.provider.importer.SesameImporterProvider.java

/** Upload the RDF data into the Sesame repository.
 * @param taskInfo The TaskInfo object describing the entire task.
 * @param subtask The details of the subtask
 * @param results HashMap representing the result of the task.
 * @return True, iff the upload succeeded.
 *///from  ww  w . j  av  a  2 s.  c o m
public final boolean uploadRDF(final TaskInfo taskInfo, final JsonNode subtask,
        final HashMap<String, String> results) {
    RepositoryManager manager = null;
    try {
        manager = RepositoryProvider.getRepositoryManager(sesameServer);

        String repositoryID = ToolkitFileUtils.getSesameRepositoryId(taskInfo);

        Repository repository = manager.getRepository(repositoryID);
        if (repository == null) {
            // Repository is missing. This is bad.
            logger.error("Sesame uploadRDF, repository missing");
            return false;
        }

        RepositoryConnection con = null;
        try {
            con = repository.getConnection();
            // If required, remove all existing triples
            if (subtask.get("clear") != null && subtask.get("clear").booleanValue()) {
                con.clear();
            }
            Path dir = Paths.get(ToolkitFileUtils.getTaskHarvestOutputPath(taskInfo));
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
                for (Path entry : stream) {
                    File file = new File(entry.toString());
                    logger.debug("Full path:" + entry.toAbsolutePath().toString());
                    con.add(file, "", Rio.getParserFormatForFileName(entry.toString()));
                }
            } catch (DirectoryIteratorException | IOException ex) {
                // I/O error encountered during the iteration,
                // the cause is an IOException
                results.put(TaskStatus.EXCEPTION, "Exception in Sesame uploadRDF");
                logger.error("Exception in Sesame uploadRDF:", ex);
                return false;
            }
        } catch (RDFParseException e) {
            results.put(TaskStatus.EXCEPTION, "Exception in Sesame uploadRDF");
            logger.error("Sesame uploadRDF, error parsing RDF: ", e);
            return false;
        } finally {
            if (con != null) {
                con.close();
            }
        }

        return true;
    } catch (RepositoryConfigException | RepositoryException e) {
        results.put(TaskStatus.EXCEPTION, "Exception in Sesame uploadRDF");
        logger.error("Exception in Sesame uploadRDF()", e);
    }
    return false;
}

From source file:org.carcv.impl.core.io.FFMPEGVideoHandlerIT.java

/**
 * Test method for {@link org.carcv.impl.core.io.FFMPEGVideoHandler#copyCarImagesToDir(java.util.List, java.nio.file.Path)}.
 *
 * @throws IOException/*from  www  .  j  a v  a 2  s .c o  m*/
 */
@Test
public void testCopyCarImagesToDir() throws IOException {
    FFMPEGVideoHandler.copyCarImagesToDir(entry.getCarImages(), videoDir);
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(videoDir);
    ArrayList<Path> paths = new ArrayList<>();
    for (Path p : dirStream) {
        paths.add(p);
    }
    dirStream.close();
    assertEquals(2, paths.size());

    Collections.sort(paths, new Comparator<Path>() {
        @Override
        public int compare(Path o1, Path o2) {
            return new CompareToBuilder().append(o1.getFileName().toString(), o2.getFileName().toString())
                    .toComparison();
        }
    });

    for (int i = 0; i < paths.size(); i++) {
        assertTrue(paths.get(i).getFileName().toString().startsWith(i + ""));
    }
}

From source file:org.wso2.carbon.apimgt.rest.api.publisher.utils.ImportExportUtils.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 APIMgtEntityImportExportException if an error occurs while listing directories
 *///from  w  ww  .j ava 2s . c o m
public static Set<String> getDirectoryList(String path) throws APIMgtEntityImportExportException {
    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) {
        throw new APIMgtEntityImportExportException("Error while listing directories under " + path, e);
    }
    return directoryNames;
}

From source file:com.splicemachine.derby.stream.control.ControlDataSetProcessor.java

private InputStream getFileStream(String s) throws IOException {
    DistributedFileSystem dfs = SIDriver.driver().fileSystem();
    InputStream value;//from   w w w. j  a  va2 s  . c  o m
    if (dfs.getInfo(s).isDirectory()) {
        //we need to open a Stream against each file in the directory
        InputStream inputStream = null;
        boolean sequenced = false;
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dfs.getPath(s))) {
            for (Path p : stream) {
                if (inputStream == null) {
                    inputStream = newInputStream(dfs, p, StandardOpenOption.READ);
                } else {
                    inputStream = new SequenceInputStream(inputStream,
                            newInputStream(dfs, p, StandardOpenOption.READ));
                }
            }
        }
        value = inputStream;
    } else {
        value = newInputStream(dfs, dfs.getPath(s), StandardOpenOption.READ);
    }
    return value;
}

From source file:company.gonapps.loghut.dao.TagDao.java

public List<TagDto> getList(String tagName, int year, int month) throws IOException, InvalidTagNameException {
    List<TagDto> tags = new LinkedList<>();
    rrwl.readLock().lock();/*  w  w w  .j a  v a  2s .c o  m*/
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get(settingDao.getSetting("tags.directory")
            + "/" + tagName + "/" + String.format("%04d", year) + "/" + String.format("%02d", month)))) {

        for (Path path : ds) {
            Matcher matcher = tagPathStringPattern.matcher(path.toString());
            if (matcher.find())
                tags.add(new TagDto().setName(matcher.group("name")).setPost(postDao.get(
                        Integer.parseInt(matcher.group("year")), Integer.parseInt(matcher.group("month")),
                        Integer.parseInt(matcher.group("day")), Integer.parseInt(matcher.group("number")),
                        matcher.group("secret").equals("s"))));
        }
    } finally {
        rrwl.readLock().unlock();
    }
    Collections.sort(tags, new TagDtoComparator());
    return tags;
}

From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

private boolean isDirectoryEmpty(Path dir) throws IOException {
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir);
    return !dirStream.iterator().hasNext();
}

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

@Test
public void testErroneousFiles() throws IOException {
    System.out.println(" |- Test erroneous files:");
    Path dir = Paths.get(SimpleFrequencyGenotypeDataTest.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 {
                SimpleDistanceMatrixData.readData(file, type);
            } catch (IOException ex) {
                thrown = true;/*from   w ww . j a va 2  s . c  o m*/
                System.out.print(ex.getMessage());
            } finally {
                System.out.println();
            }
            assertTrue("File " + file + " should throw exception.", thrown);
        }
    }
}

From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java

@Override
public List<Bucket> listBuckets() throws AmazonClientException {
    List<Bucket> result = new ArrayList<>();
    try {//from   w ww .ja  v a 2 s . c o m
        for (Path path : Files.newDirectoryStream(base)) {
            String bucketName = path.getFileName().toString();
            Bucket bucket = new Bucket(bucketName);
            bucket.setOwner(getOwner(bucketName));
            bucket.setCreationDate(
                    new Date(Files.readAttributes(path, BasicFileAttributes.class).creationTime().toMillis()));
            result.add(bucket);
        }
    } catch (IOException e) {
        throw new AmazonClientException(e);
    }
    return result;
}