下面列出了怎么用java.nio.file.DirectoryIteratorException的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
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;
}
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();
}
}
@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");
}
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();
}
}
/**
* 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;
}
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;
}
@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;
}
/**
* 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;
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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);
}
}
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();
}
@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());
}
@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());
}
@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);
}
}
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));
}
}
@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));
}
}
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;
}
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) {}
}
@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);
}
}
@Override
public boolean hasNext() {
try {
return (getNext() != null);
} catch (IOException e) {
FileUtils.closeQuietly(this);
throw new DirectoryIteratorException(e);
}
}
@Override
public T next() {
T result;
try {
result = getNext();
} catch (IOException e) {
throw new DirectoryIteratorException(e);
}
next = null;
return result;
}
@Override
public boolean hasNext() {
try {
return (getNextMatchingEntry() != null);
} catch (IOException e) {
throw new DirectoryIteratorException(e);
}
}
@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);
}
}
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;
}
/**
* 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);
}
}
}
/**
* 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();
}
}