java.nio.file.DirectoryIteratorException Java Examples

The following examples show how to use java.nio.file.DirectoryIteratorException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: presto   Author: prestosql   File: KinesisTableDescriptionSupplier.java    License: Apache License 2.0 6 votes vote down vote up
private static List<Path> listFiles(Path path)
{
    if (path == null || !Files.isDirectory(path)) {
        throw new PrestoException(KinesisErrorCode.KINESIS_METADATA_EXCEPTION, "Table description location does not exist or is not a directory");
    }
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
        ImmutableList.Builder<Path> builder = ImmutableList.builder();
        for (Path file : stream) {
            builder.add(file);
        }

        return builder.build();
    }
    catch (IOException | DirectoryIteratorException e) {
        throwIfUnchecked(e);
        throw new RuntimeException(e);
    }
}
 
Example #2
Source Project: uyuni   Author: uyuni-project   File: CACertPathUtil.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static String findRpmCACert(Path docrootPath) {
    String candidateRpmCA = StringUtils.EMPTY;
    try (DirectoryStream<Path> directoryStream =
            Files.newDirectoryStream(docrootPath, CA_CRT_RPM_NAME + GLOB_NOARCH_RPM)) {
        for (Path rpmFile : directoryStream) {
            logger.debug("Found CA RPM file: " + candidateRpmCA);
            if (rpmFile.toString().compareTo(candidateRpmCA) > 0) {
                candidateRpmCA = rpmFile.toString();
            }
        }
        return candidateRpmCA;
    }
    catch (IOException | DirectoryIteratorException ex) {
        logger.warn("Cannot scan docroot " + docrootPath +
                " for CA RPM certificate. Exception: " + ex);
    }
    return candidateRpmCA;
}
 
Example #3
Source Project: Bytecoder   Author: mirkosertic   File: PollingWatchService.java    License: Apache License 2.0 6 votes vote down vote up
PollingWatchKey(Path dir, PollingWatchService watcher, Object fileKey)
    throws IOException
{
    super(dir, watcher);
    this.fileKey = fileKey;
    this.valid = true;
    this.tickCount = 0;
    this.entries = new HashMap<Path,CacheEntry>();

    // get the initial entries in the directory
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path entry: stream) {
            // don't follow links
            long lastModified =
                Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis();
            entries.put(entry.getFileName(), new CacheEntry(lastModified, tickCount));
        }
    } catch (DirectoryIteratorException e) {
        throw e.getCause();
    }
}
 
Example #4
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: PackageOptions.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testEmptyPackageDirectory(Path base) throws Exception {
    Path src = base.resolve("src");
    createSources(src);

    // need an empty package directory, to check whether
    // the behavior of subpackage and package
    Path pkgdir = src.resolve("m1/m1pro/");
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(pkgdir, "*.java")) {
        for (Path entry : stream) {
            Files.deleteIfExists(entry);
        }
    } catch (DirectoryIteratorException ex) {
        // I/O error encounted during the iteration
        throw ex.getCause();
    }
    execTask("--module-source-path", src.toString(),
            "-subpackages", "m1/m1pro");

    checkPackagesSpecified("m1pro", "m1pro.pro1", "m1pro.pro2");

    // empty package directory should cause an error
    execNegativeTask("--module-source-path", src.toString(),
                     "m1/m1pro");

}
 
Example #5
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: PollingWatchService.java    License: GNU General Public License v2.0 6 votes vote down vote up
PollingWatchKey(Path dir, PollingWatchService watcher, Object fileKey)
    throws IOException
{
    super(dir, watcher);
    this.fileKey = fileKey;
    this.valid = true;
    this.tickCount = 0;
    this.entries = new HashMap<Path,CacheEntry>();

    // get the initial entries in the directory
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path entry: stream) {
            // don't follow links
            long lastModified =
                Files.getLastModifiedTime(entry, LinkOption.NOFOLLOW_LINKS).toMillis();
            entries.put(entry.getFileName(), new CacheEntry(lastModified, tickCount));
        }
    } catch (DirectoryIteratorException e) {
        throw e.getCause();
    }
}
 
Example #6
Source Project: hadoop   Author: naver   File: IOUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the complete list of files in a directory as strings.<p/>
 *
 * 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;
}
 
Example #7
Source Project: dremio-oss   Author: dremio   File: FileSelection.java    License: Apache License 2.0 6 votes vote down vote up
public static FileSelection create(final FileSystem fs, Path combined) throws IOException {
  Stopwatch timer = Stopwatch.createStarted();

  // NFS filesystems has delay before files written by executor shows up in the coordinator.
  // For NFS, fs.exists() will force a refresh if the directory is not found
  // No action is taken if it returns false as the code path already handles the Exception case
  fs.exists(combined);

  final ImmutableList<FileAttributes> fileAttributes;
  try(DirectoryStream<FileAttributes> stream = FileSystemUtils.globRecursive(fs, combined, NO_HIDDEN_FILES)) {
    fileAttributes = ImmutableList.copyOf(stream);
  } catch (DirectoryIteratorException e) {
    throw e.getCause();
  }

  logger.trace("Returned files are: {}", fileAttributes);
  if (fileAttributes == null || fileAttributes.isEmpty()) {
    return null;
  }

  final FileSelection fileSel = createFromExpanded(fileAttributes, combined.toURI().getPath());
  logger.debug("FileSelection.create() took {} ms ", timer.elapsed(TimeUnit.MILLISECONDS));
  return fileSel;
}
 
Example #8
Source Project: dremio-oss   Author: dremio   File: NativeLibJarPluginLoader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ClassLoader loadPlugin(Path pluginPath, PluginDescriptor pluginDescriptor) {
  final PluginClassLoader pluginClassLoader = new NativeLibPluginClassLoader(pluginPath, this.pluginManager, pluginDescriptor, this.getClass().getClassLoader());
  pluginClassLoader.addFile(pluginPath.toFile());

  // Add the subdirectory for any customer added dependencies.
  final Path dependencyPath = pluginPath.getParent().resolve(pluginDescriptor.getPluginId() + ".d");
  try (final DirectoryStream<Path> files = Files.newDirectoryStream(dependencyPath)) {
    for (final Path file : files) {
      final URL fileUrl = file.toUri().toURL();
      logger.debug("Loaded dependency for {}: {}", pluginDescriptor.getPluginId(), fileUrl.toString());
      pluginClassLoader.addURL(fileUrl);
    }
  } catch (NoSuchFileException nfe) {
    // Do nothing, the subdirectory doesn't exist.
  } catch (DirectoryIteratorException | IOException e) {
    logger.warn(String.format("Unable to add dependency directory for plugin %s", pluginDescriptor.getPluginId()), e);
  }

  return pluginClassLoader;
}
 
Example #9
Source Project: big-c   Author: yncxcw   File: IOUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the complete list of files in a directory as strings.<p/>
 *
 * 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;
}
 
Example #10
Source Project: hibernate5-ddl-maven-plugin   Author: jpdigital   File: DdlMojoTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Resets the Mojo by setting {@link #mojo} to {@code null} and deletes the
 * test directory.
 *
 * @throws IOException Thrown if the test directory could not be deleted
 */
@After
public void tearDown() throws IOException {
    //Unset Mojo instance
    mojo = null;

    //Delete test directory
    final Path testDir = Paths.get(TEST_DIR);
    if (Files.exists(testDir)) {
        //First get all files in the test directory (if the test directory
        //exists and delete them. This is necessary because there is no
        //method for recursivly deleting a directory in the Java API.
        try (final DirectoryStream<Path> files = Files.newDirectoryStream(
            testDir)) {
            for (final Path file : files) {
                Files.deleteIfExists(file);
            }
        } catch (DirectoryIteratorException ex) {
            throw ex.getCause();
        }
        //Delete the (now empty) test directory.
        Files.deleteIfExists(testDir);
    }
}
 
Example #11
Source Project: hibernate5-ddl-maven-plugin   Author: jpdigital   File: DdlMojoTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Resets the Mojo by setting {@link #mojo} to {@code null} and deletes the
 * test directory.
 *
 * @throws IOException Thrown if the test directory could not be deleted
 */
@After
public void tearDown() throws IOException {
    //Unset Mojo instance
    mojo = null;

    //Delete test directory
    final Path testDir = Paths.get(TEST_DIR);
    if (Files.exists(testDir)) {
        //First get all files in the test directory (if the test directory
        //exists and delete them. This is necessary because there is no
        //method for recursivly deleting a directory in the Java API.
        try (final DirectoryStream<Path> files = Files.newDirectoryStream(
            testDir)) {
            for (final Path file : files) {
                Files.deleteIfExists(file);
            }
        } catch (DirectoryIteratorException ex) {
            throw ex.getCause();
        }
        //Delete the (now empty) test directory.
        Files.deleteIfExists(testDir);
    }
}
 
Example #12
Source Project: hibernate5-ddl-maven-plugin   Author: jpdigital   File: DdlMojoTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Resets the Mojo by setting {@link #mojo} to {@code null} and deletes the
 * test directory.
 *
 * @throws IOException Thrown if the test directory could not be deleted
 */
@After
public void tearDown() throws IOException {
    //Unset Mojo instance
    mojo = null;

    //Delete test directory
    final Path testDir = Paths.get(TEST_DIR);
    if (Files.exists(testDir)) {
        //First get all files in the test directory (if the test directory
        //exists and delete them. This is necessary because there is no
        //method for recursivly deleting a directory in the Java API.
        try (final DirectoryStream<Path> files = Files.newDirectoryStream(
            testDir)) {
            for (final Path file : files) {
                Files.deleteIfExists(file);
            }
        } catch (DirectoryIteratorException ex) {
            throw ex.getCause();
        }
        //Delete the (now empty) test directory.
        Files.deleteIfExists(testDir);
    }
}
 
Example #13
Source Project: hibernate5-ddl-maven-plugin   Author: jpdigital   File: DdlMojoTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Resets the Mojo by setting {@link #mojo} to {@code null} and deletes the
 * test directory.
 *
 * @throws IOException Thrown if the test directory could not be deleted
 */
@After
public void tearDown() throws IOException {
    //Unset Mojo instance
    mojo = null;

    //Delete test directory
    final Path testDir = Paths.get(TEST_DIR);
    if (Files.exists(testDir)) {
        //First get all files in the test directory (if the test directory
        //exists and delete them. This is necessary because there is no
        //method for recursivly deleting a directory in the Java API.
        try (final DirectoryStream<Path> files = Files.newDirectoryStream(
            testDir)) {
            for (final Path file : files) {
                Files.deleteIfExists(file);
            }
        } catch (DirectoryIteratorException ex) {
            throw ex.getCause();
        }
        //Delete the (now empty) test directory.
        Files.deleteIfExists(testDir);
    }
}
 
Example #14
Source Project: hibernate5-ddl-maven-plugin   Author: jpdigital   File: DdlMojoTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Resets the Mojo by setting {@link #mojo} to {@code null} and deletes the
 * test directory.
 *
 * @throws IOException Thrown if the test directory could not be deleted
 */
@After
public void tearDown() throws IOException {
    //Unset Mojo instance
    mojo = null;

    //Delete test directory
    final Path testDir = Paths.get(TEST_DIR);
    if (Files.exists(testDir)) {
        //First get all files in the test directory (if the test directory
        //exists and delete them. This is necessary because there is no
        //method for recursivly deleting a directory in the Java API.
        try (final DirectoryStream<Path> files = Files.newDirectoryStream(
            testDir)) {
            for (final Path file : files) {
                Files.deleteIfExists(file);
            }
        } catch (DirectoryIteratorException ex) {
            throw ex.getCause();
        }
        //Delete the (now empty) test directory.
        Files.deleteIfExists(testDir);
    }
}
 
Example #15
Source Project: presto-kinesis   Author: qubole   File: KinesisTableDescriptionSupplier.java    License: Apache License 2.0 6 votes vote down vote up
private static List<Path> listFiles(Path dir)
{
    if ((dir != null) && Files.isDirectory(dir)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            ImmutableList.Builder<Path> builder = ImmutableList.builder();
            for (Path file : stream) {
                builder.add(file);
            }

            return builder.build();
        }
        catch (IOException | DirectoryIteratorException x) {
            log.warn(x, "Warning.");
            throw Throwables.propagate(x);
        }
    }
    return ImmutableList.of();
}
 
Example #16
Source Project: container   Author: OpenTOSCA   File: FileSystemDirectory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Set<AbstractDirectory> getDirectories() {
    Set<Path> result = new HashSet<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(representedPath)) {
        for (Path entry : stream) {
            if (Files.isDirectory(entry)) {
                result.add(entry);
            }
        }
    } catch (DirectoryIteratorException ex) {
        // I/O error encounted during the iteration, the cause is an IOException
        throw new UncheckedIOException((IOException) ex.getCause());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return result.stream().map(FileSystemDirectory::new).collect(Collectors.toSet());
}
 
Example #17
Source Project: container   Author: OpenTOSCA   File: FileSystemDirectory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Set<AbstractFile> getFilesNotConsiderPatterns() {
    Set<Path> result = new HashSet<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(representedPath)) {
        for (Path entry : stream) {
            if (Files.isRegularFile(entry)) {
                result.add(entry);
            }
        }
    } catch (DirectoryIteratorException ex) {
        // I/O error encounted during the iteration, the cause is an IOException
        throw new UncheckedIOException((IOException) ex.getCause());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return result.stream().map(FileSystemFile::new).collect(Collectors.toSet());
}
 
Example #18
Source Project: jimfs   Author: google   File: JimfsSecureDirectoryStream.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected synchronized Path computeNext() {
  checkOpen();

  try {
    if (fileNames == null) {
      fileNames = view.snapshotWorkingDirectoryEntries().iterator();
    }

    while (fileNames.hasNext()) {
      Name name = fileNames.next();
      Path path = view.getWorkingDirectoryPath().resolve(name);

      if (filter.accept(path)) {
        return path;
      }
    }

    return endOfData();
  } catch (IOException e) {
    throw new DirectoryIteratorException(e);
  }
}
 
Example #19
Source Project: mycore   Author: MyCoRe-Org   File: MCRDirectoryStream.java    License: GNU General Public License v3.0 5 votes vote down vote up
private MCRPath getPath(MCRFilesystemNode[] children, int index) {
    try {
        MCRPath path = MCRPath.toMCRPath(mcrDirectoryStream.path.resolve(children[index].getName()));
        LOGGER.debug(() -> "getting path at index " + index + ": " + path);
        return path;
    } catch (RuntimeException e) {
        throw new DirectoryIteratorException(new IOException(e));
    }
}
 
Example #20
Source Project: sftp-fs   Author: robtimus   File: SFTPFileSystemDirectoryStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testThrowWhileIterating() throws IOException {
    addFile("/foo");

    try (DirectoryStream<Path> stream = fileSystem.newDirectoryStream(createPath("/"), ThrowingFilter.INSTANCE)) {
        DirectoryIteratorException exception = assertThrows(DirectoryIteratorException.class, () -> {
            for (Iterator<Path> iterator = stream.iterator(); iterator.hasNext(); ) {
                iterator.next();
            }
        });
        assertThat(exception.getCause(), instanceOf(IOException.class));
    }
}
 
Example #21
Source Project: jdk8u_jdk   Author: JetBrains   File: TCChartReporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static List<Path> listResFiles(Path dir, String pattern) throws IOException {
    List<Path> result = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, pattern)) {
        for (Path entry : stream) {
            result.add(entry);
        }
    } catch (DirectoryIteratorException ex) {
        throw ex.getCause();
    }
    return result;
}
 
Example #22
Source Project: j2objc   Author: google   File: DirectoryIteratorExceptionTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_constructor() {
    IOException ioException = new IOException();
    DirectoryIteratorException exception = new DirectoryIteratorException(ioException);

    assertSame(ioException, exception.getCause());

    try {
        new DirectoryIteratorException(null);
        fail();
    } catch (NullPointerException expected) {}
}
 
Example #23
Source Project: CloverETL-Engine   Author: CloverETL   File: WildcardDirectoryStream.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public DirectoryStream<Input> next() {
	try {
		FileUtils.close(directoryStream); // close the previous stream
		String fileName = patterns.next();
		directoryStream = newDirectoryStream(fileName);
		return directoryStream;
	} catch (IOException ioe) {
		throw new DirectoryIteratorException(ioe);
	}
}
 
Example #24
Source Project: CloverETL-Engine   Author: CloverETL   File: Wildcards.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean hasNext() {
	try {
		return (getNext() != null);
	} catch (IOException e) {
		FileUtils.closeQuietly(this);
		throw new DirectoryIteratorException(e);
	}
}
 
Example #25
Source Project: CloverETL-Engine   Author: CloverETL   File: Wildcards.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public T next() {
	T result;
	try {
		result = getNext();
	} catch (IOException e) {
		throw new DirectoryIteratorException(e);
	}
	next = null;
	return result;
}
 
Example #26
Source Project: CloverETL-Engine   Author: CloverETL   File: ArchiveDirectoryStream.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean hasNext() {
	try {
		return (getNextMatchingEntry() != null);
	} catch (IOException e) {
		throw new DirectoryIteratorException(e);
	}
}
 
Example #27
Source Project: CloverETL-Engine   Author: CloverETL   File: ArchiveDirectoryStream.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Input next() {
	try {
		Entry entry = getNextMatchingEntry();
		if (entry == null) {
			throw new NoSuchElementException();
		}
		Input input = getEntryInput(entry);
		cachedEntry = null;
		return input;
	} catch (IOException e) {
		throw new DirectoryIteratorException(e);
	}
}
 
Example #28
Source Project: batfish   Author: batfish   File: WorkMgr.java    License: Apache License 2.0 5 votes vote down vote up
private static SortedSet<Path> getEntries(Path directory) {
  SortedSet<Path> entries = new TreeSet<>();
  try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
    for (Path entry : stream) {
      entries.add(entry);
    }
  } catch (IOException | DirectoryIteratorException e) {
    throw new BatfishException("Error listing directory '" + directory + "'", e);
  }
  return entries;
}
 
Example #29
Source Project: carbon-apimgt   Author: wso2   File: APIImportUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method adds API sequences to the imported API. If the sequence is a newly defined one, it is added.
 *
 * @param pathToArchive location of the extracted folder of the API
 */
private static void addSOAPToREST(String pathToArchive, API importedApi, Registry registry)
        throws APIImportExportException {

    String inFlowFileLocation = pathToArchive + File.separator + SOAPTOREST + File.separator + IN;
    String outFlowFileLocation = pathToArchive + File.separator + SOAPTOREST + File.separator + OUT;

    //Adding in-sequence, if any
    if (CommonUtil.checkFileExistence(inFlowFileLocation)) {
        APIIdentifier apiId = importedApi.getId();
        String soapToRestLocationIn =
                APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName()
                        + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR
                        + apiId.getVersion() + RegistryConstants.PATH_SEPARATOR
                        + SOAPToRESTConstants.SequenceGen.SOAP_TO_REST_IN_RESOURCE;
        String soapToRestLocationOut =
                APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiId.getProviderName()
                        + RegistryConstants.PATH_SEPARATOR + apiId.getApiName() + RegistryConstants.PATH_SEPARATOR
                        + apiId.getVersion() + RegistryConstants.PATH_SEPARATOR
                        + SOAPToRESTConstants.SequenceGen.SOAP_TO_REST_OUT_RESOURCE;
        try {
            // Import inflow mediation logic
            Path inFlowDirectory = Paths.get(inFlowFileLocation);
            ImportMediationLogic(inFlowDirectory, registry, soapToRestLocationIn);

            // Import outflow mediation logic
            Path outFlowDirectory = Paths.get(outFlowFileLocation);
            ImportMediationLogic(outFlowDirectory, registry, soapToRestLocationOut);

        } catch (DirectoryIteratorException e) {
            throw new APIImportExportException("Error in importing SOAP to REST mediation logic", e);
        }
    }
}
 
Example #30
Source Project: util   Author: indeedeng   File: Directories.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Count the number of entries in a directory.
 *
 * @param dir directory to evaluate
 * @return number of inodes under it.
 * @throws IOException
 */
@Nonnegative
public static int count(@Nonnull final Path dir) throws IOException {
    try (final DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        return Iterables.size(stream);
    } catch (DirectoryIteratorException ex) {
        // I/O error encounted during the iteration, the cause is an IOException
        throw ex.getCause();
    }
}