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:com.mweagle.tereus.commands.evaluation.common.LambdaUtils.java

protected void createStableZip(ZipOutputStream zipOS, Path parentDirectory, Path archiveRoot, MessageDigest md)
        throws IOException {
    // Sort & zip files
    final List<Path> childDirectories = new ArrayList<>();
    final List<Path> childFiles = new ArrayList<>();
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(parentDirectory);
    for (Path eachChild : dirStream) {
        if (Files.isDirectory(eachChild)) {
            childDirectories.add(eachChild);
        } else {/*from  w ww .j a va2  s .  c  o  m*/
            childFiles.add(eachChild);
        }
    }
    final int archiveRootLength = archiveRoot.toAbsolutePath().toString().length() + 1;
    childFiles.stream().sorted().forEach(eachPath -> {
        final String zeName = eachPath.toAbsolutePath().toString().substring(archiveRootLength);
        try {
            final ZipEntry ze = new ZipEntry(zeName);
            zipOS.putNextEntry(ze);
            Files.copy(eachPath, zipOS);
            md.update(Files.readAllBytes(eachPath));
            zipOS.closeEntry();
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    });

    childDirectories.stream().sorted().forEach(eachPath -> {
        try {
            createStableZip(zipOS, eachPath, archiveRoot, md);
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    });
}

From source file:org.nuxeo.ecm.core.transientstore.AbstractTransientStore.java

@Override
public void doGC() {
    log.debug(String.format("Performing GC for TransientStore %s", config.getName()));
    long newSize = 0;
    try {/*w w  w .j  a  v  a 2 s .  com*/
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(cacheDir.getAbsolutePath()))) {
            for (Path entry : stream) {
                String key = getKeyCachingDirName(entry.getFileName().toString());
                try {
                    if (exists(key)) {
                        newSize += getFilePathSize(entry);
                        continue;
                    }
                    FileUtils.deleteDirectory(entry.toFile());
                } catch (IOException e) {
                    log.error("Error while performing GC", e);
                }
            }
        }
    } catch (IOException e) {
        log.error("Error while performing GC", e);
    }
    setStorageSize(newSize);
}

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

/**
 * Called every minute to monitor the "batch-sets" folder. If a batch-set zip file has been
 * placed in this folder, the batch-set gets executed.
 *//*from w  w  w  . ja va  2 s  . co  m*/
@Schedule(persistent = false, second = "24", minute = "*/1", hour = "*/1")
protected void monitorBatchJobInFolderInitiation() {

    Path batchSetsFolder = batchService.getBatchJobRoot().resolve(BATCH_SETS_FOLDER);

    if (Files.isDirectory(batchSetsFolder)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(batchSetsFolder)) {
            for (Path p : stream) {
                if (Files.isReadable(p) && Files.isRegularFile(p)) {
                    try {
                        executeBatchSetFromArchiveOrFolder(p);
                    } catch (Exception e) {
                        log.error("Error executing batch set " + p, e);
                    } finally {
                        // Delete the file
                        try {
                            Files.delete(p);
                        } catch (IOException ignored) {
                        }
                    }
                }
            }
        } catch (IOException ignored) {
        }
    }
}

From source file:org.esa.s2tbx.dataio.s2.Sentinel2ProductReader.java

/**
 * From a product path, search a jpeg file for the given resolution, extract tile layout
 * information and update/*  ww w.  j  a v a  2 s  .  c om*/
 *
 * @param productMetadataFilePath the complete path to the product metadata file
 * @param resolution              the resolution for which we wan to find the tile layout
 * @return the tile layout for the resolution, or {@code null} if none was found
 */
public TileLayout retrieveTileLayoutFromProduct(Path productMetadataFilePath, S2SpatialResolution resolution) {
    TileLayout tileLayoutForResolution = null;

    if (Files.exists(productMetadataFilePath) && productMetadataFilePath.toString().endsWith(".xml")) {
        Path productFolder = productMetadataFilePath.getParent();
        Path granulesFolder = productFolder.resolve("GRANULE");
        try {
            DirectoryStream<Path> granulesFolderStream = Files.newDirectoryStream(granulesFolder);

            for (Path granulePath : granulesFolderStream) {
                tileLayoutForResolution = retrieveTileLayoutFromGranuleDirectory(granulePath, resolution);
                if (tileLayoutForResolution != null) {
                    break;
                }
            }
        } catch (IOException e) {
            SystemUtils.LOG.warning("Could not retrieve tile layout for product "
                    + productMetadataFilePath.toAbsolutePath().toString() + " error returned: "
                    + e.getMessage());
        }
    }

    return tileLayoutForResolution;
}

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

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

From source file:org.apache.storm.daemon.logviewer.utils.DirectoryCleaner.java

/**
 * Lists files in directory./*from  w  w  w  . j  a  v a2  s  .  c  om*/
 * Note that to avoid memory problem, we only return the first 1024 files in a directory.
 *
 * @param dir directory to get file list
 * @return files in directory
 */
public List<Path> getFilesForDir(Path dir) throws IOException {
    List<Path> files = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path path : stream) {
            files.add(path);
            if (files.size() >= MAX_NUMBER_OF_FILES_FOR_DIR) {
                break;
            }
        }
    } catch (IOException e) {
        numFileOpenExceptions.mark();
        throw e;
    }
    return files;
}

From source file:com.shmsoft.dmass.main.ActionStaging.java

private long dirSize(Path path) {
    long size = 0;
    try {//  w  w w  .  j a v a  2 s  .  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) {
        e.printStackTrace();
    }
    return size;
}

From source file:org.apache.tika.batch.fs.FSBatchTestBase.java

/**
 * helper method equivalent to File#listFiles()
 * grabs children only, does not walk recursively
 * @param p//from w  ww  .  ja va 2 s. c o m
 * @return
 */
public static List<Path> listPaths(Path p) throws IOException {
    List<Path> list = new ArrayList<>();
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(p)) {
        Iterator<Path> it = ds.iterator();
        while (it.hasNext()) {
            list.add(it.next());
        }
    }
    return list;
}

From source file:org.apache.karaf.tooling.ArchiveMojo.java

private void addFileToZip(ZipArchiveOutputStream tOut, Path f, String base) throws IOException {
    if (Files.isDirectory(f)) {
        String entryName = base + f.getFileName().toString() + "/";
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        tOut.putArchiveEntry(zipEntry);//w  w w .  ja  v  a2 s.co m
        tOut.closeArchiveEntry();
        try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) {
            for (Path child : children) {
                addFileToZip(tOut, child, entryName);
            }
        }
    } else if (useSymLinks && Files.isSymbolicLink(f)) {
        String entryName = base + f.getFileName().toString();
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        zipEntry.setUnixMode(UnixStat.LINK_FLAG | UnixStat.DEFAULT_FILE_PERM);
        tOut.putArchiveEntry(zipEntry);
        tOut.write(Files.readSymbolicLink(f).toString().getBytes());
        tOut.closeArchiveEntry();
    } else {
        String entryName = base + f.getFileName().toString();
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        zipEntry.setSize(Files.size(f));
        if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin"))) {
            if (!entryName.endsWith(".bat")) {
                zipEntry.setUnixMode(0755);
            } else {
                zipEntry.setUnixMode(0644);
            }
        }
        tOut.putArchiveEntry(zipEntry);
        Files.copy(f, tOut);
        tOut.closeArchiveEntry();
    }
}

From source file:org.dcache.xrootd.standalone.DataServerHandler.java

@Override
protected DirListResponse doOnDirList(ChannelHandlerContext context, DirListRequest request)
        throws XrootdException {
    String listPath = request.getPath();
    if (listPath.isEmpty()) {
        throw new XrootdException(kXR_ArgMissing, "no source path specified");
    }//w w  w .j  ava2  s .  c o m

    Path dir = getFile(listPath).toPath();
    try (DirectoryStream<Path> paths = Files.newDirectoryStream(dir)) {
        DirListResponse.Builder builder = DirListResponse.builder(request);
        for (Path path : paths) {
            builder.add(path.getFileName().toString(),
                    request.isDirectoryStat() ? getFileStatusOf(path.toFile()) : null);
            if (builder.count() >= 1000) {
                respond(context, builder.buildPartial());
            }
        }
        return builder.buildFinal();
    } catch (FileNotFoundException e) {
        throw new XrootdException(kXR_NotFound, "No such directory: " + dir);
    } catch (NotDirectoryException e) {
        throw new XrootdException(kXR_IOError, "Not a directory: " + dir);
    } catch (IOException e) {
        throw new XrootdException(kXR_IOError, "IO Error: " + dir);
    }
}