當前位置: 首頁>>代碼示例>>Java>>正文


Java Files.newDirectoryStream方法代碼示例

本文整理匯總了Java中java.nio.file.Files.newDirectoryStream方法的典型用法代碼示例。如果您正苦於以下問題:Java Files.newDirectoryStream方法的具體用法?Java Files.newDirectoryStream怎麽用?Java Files.newDirectoryStream使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.nio.file.Files的用法示例。


在下文中一共展示了Files.newDirectoryStream方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: findImageFileWithExtension

import java.nio.file.Files; //導入方法依賴的package包/類
private Path findImageFileWithExtension(Path dir, String ext) {
  Path file = null;
  try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir, "*." + ext)) {
    Iterator<Path> imageIter = dirStream.iterator();
    if (!imageIter.hasNext()) {
      throw new IllegalStateException("No " + ext + " image file in " + dir);
    }
    file = imageIter.next();
    if (imageIter.hasNext()) {
      throw new IllegalStateException("Multiple " + ext + " image files in " + dir);
    }
  } catch (IOException e) {
    throw new IllegalStateException("Error finding " + ext + " image file in " + dir, e);
  }
  if (!readablePredicate().test(file)) {
    throw new IllegalStateException("Image file is not not readable: " + file);
  }
  return file;
}
 
開發者ID:google,項目名稱:ios-device-control,代碼行數:20,代碼來源:DevDiskImages.java

示例2: deleteRecursivelyInsecure

import java.nio.file.Files; //導入方法依賴的package包/類
/**
 * Insecure recursive delete for file systems that don't support {@code SecureDirectoryStream}.
 * Returns a collection of exceptions that occurred or null if no exceptions were thrown.
 */
@Nullable
private static Collection<IOException> deleteRecursivelyInsecure(Path path) {
  Collection<IOException> exceptions = null;
  try {
    if (Files.isDirectory(path, NOFOLLOW_LINKS)) {
      try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
        exceptions = deleteDirectoryContentsInsecure(stream);
      }
    }

    // If exceptions is not null, something went wrong trying to delete the contents of the
    // directory, so we shouldn't try to delete the directory as it will probably fail.
    if (exceptions == null) {
      Files.delete(path);
    }

    return exceptions;
  } catch (IOException e) {
    return addException(exceptions, e);
  }
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:26,代碼來源:MoreFiles.java

示例3: ensureNoPre019State

import java.nio.file.Files; //導入方法依賴的package包/類
/**
 * Throws an IAE if a pre 0.19 state is detected
 */
private void ensureNoPre019State() throws Exception {
    for (Path dataLocation : nodeEnv.nodeDataPaths()) {
        final Path stateLocation = dataLocation.resolve(MetaDataStateFormat.STATE_DIR_NAME);
        if (!Files.exists(stateLocation)) {
            continue;
        }
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(stateLocation)) {
            for (Path stateFile : stream) {
                if (logger.isTraceEnabled()) {
                    logger.trace("[upgrade]: processing [{}]", stateFile.getFileName());
                }
                final String name = stateFile.getFileName().toString();
                if (name.startsWith("metadata-")) {
                    throw new IllegalStateException("Detected pre 0.19 metadata file please upgrade to a version before "
                            + Version.CURRENT.minimumCompatibilityVersion()
                            + " first to upgrade state structures - metadata found: [" + stateFile.getParent().toAbsolutePath());
                }
            }
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:25,代碼來源:GatewayMetaState.java

示例4: children

import java.nio.file.Files; //導入方法依賴的package包/類
@Override
public String[] children(String f) {
    Path p = getPath(f);
    try (DirectoryStream<Path> dir = Files.newDirectoryStream(p)){
        java.util.List<String> result = new ArrayList<>();
        for (Path child : dir) {
            String name = child.getName(child.getNameCount() - 1).toString();
            if (name.endsWith("/"))
                name = name.substring(0, name.length() - 1);
            result.add(name);
        }

        return result.toArray(new String[result.size()]);
    } catch (IOException ex) {
        return new String[0]; //huh?
    }
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:18,代碼來源:NBJRTFileSystem.java

示例5: findJsonSpec

import java.nio.file.Files; //導入方法依賴的package包/類
/**
 * Returns the json files found within the directory provided as argument.
 * Files are looked up in the classpath, or optionally from {@code fileSystem} if its not null.
 */
public static Set<Path> findJsonSpec(FileSystem fileSystem, String optionalPathPrefix, String path) throws IOException {
    Path dir = resolveFile(fileSystem, optionalPathPrefix, path, null);

    if (!Files.isDirectory(dir)) {
        throw new NotDirectoryException(path);
    }

    Set<Path> jsonFiles = new HashSet<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path item : stream) {
            if (item.toString().endsWith(JSON_SUFFIX)) {
                jsonFiles.add(item);
            }
        }
    }

    if (jsonFiles.isEmpty()) {
        throw new NoSuchFileException(path, null, "no json files found");
    }

    return jsonFiles;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:27,代碼來源:FileUtils.java

示例6: installCertificates

import java.nio.file.Files; //導入方法依賴的package包/類
private void installCertificates(Path path, KeyStore keyStore)
    throws IOException, CertificateException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

  try (DirectoryStream<Path> paths = Files.newDirectoryStream(path, "*.{crt,pem}")) {
    for (Path certPath : paths) {
      logger.info("installing cert from path {}", certPath.toRealPath());
      if (Files.isRegularFile(certPath)) {
        try (InputStream inputStream = Files.newInputStream(certPath)) {
          Certificate cert = certificateFactory.generateCertificate(inputStream);
          String alias = certPath.getFileName().toString();
          keyStore.setCertificateEntry(alias, cert);
          logger.info("ok, installed cert with alias {} from path {}", alias,
              certPath.toRealPath());
        } catch (Exception e) {
          logger.warn("error, skipping cert, path {} {}", certPath.toRealPath(), e.getMessage());
        }
      } else {
        logger.info("skipping cert, not a regular file {}", certPath.toRealPath());
      }
    }
  }
}
 
開發者ID:dehora,項目名稱:outland,代碼行數:24,代碼來源:CertificateLoader.java

示例7: PollingWatchKey

import java.nio.file.Files; //導入方法依賴的package包/類
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();
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:22,代碼來源:PollingWatchService.java

示例8: getClassPaths

import java.nio.file.Files; //導入方法依賴的package包/類
private List<Path> getClassPaths(String cpaths) {
    if (cpaths.isEmpty()) {
        return Collections.emptyList();
    }
    List<Path> paths = new ArrayList<>();
    for (String p : cpaths.split(File.pathSeparator)) {
        if (p.length() > 0) {
            // wildcard to parse all JAR files e.g. -classpath dir/*
            int i = p.lastIndexOf(".*");
            if (i > 0) {
                Path dir = Paths.get(p.substring(0, i));
                try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.jar")) {
                    for (Path entry : stream) {
                        paths.add(entry);
                    }
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            } else {
                paths.add(Paths.get(p));
            }
        }
    }
    return paths;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:26,代碼來源:JdepsConfiguration.java

示例9: loadFonts

import java.nio.file.Files; //導入方法依賴的package包/類
/** Load all fonts from 'assets/fonts'. **/
private void loadFonts() {
	try (DirectoryStream<Path> directoryStream =
				 Files.newDirectoryStream(Main.getInstance().getPluginProxy().getAssetsDirPath().resolve("fonts"))) {
		for (Path fontPath : directoryStream) {
			if (fontPath.getFileName().toString().endsWith(".ttf")) {
				Font.loadFont(Files.newInputStream(fontPath), 10);
			}
		}
	} catch (IOException e) {
		Main.log(e);
	}
	Balloon.setDefaultFont(Main.getProperties().getString("balloon.font"));
	LocalFont.setDefaultFont(Main.getProperties().getString("interface.font"));
}
 
開發者ID:DeskChan,項目名稱:DeskChan,代碼行數:16,代碼來源:App.java

示例10: main

import java.nio.file.Files; //導入方法依賴的package包/類
public static void main(String[] args) throws IOException
{
   Scanner input = new Scanner(System.in);

   System.out.println("Enter file or directory name:");

   // create Path object based on user input
   Path path = Paths.get(input.nextLine());

   if (Files.exists(path)) // if path exists, output info about it
   {
      // display file (or directory) information
   	System.out.printf("%n%s exists%n", path.getFileName());
   	System.out.printf("%s a directory%n", 
   		Files.isDirectory(path) ? "Is" : "Is not");
   	System.out.printf("%s an absolute path%n", 
   		path.isAbsolute() ? "Is" : "Is not");
   	System.out.printf("Last modified: %s%n", 
   		Files.getLastModifiedTime(path));
   	System.out.printf("Size: %s%n", Files.size(path));
   	System.out.printf("Path: %s%n", path);
   	System.out.printf("Absolute path: %s%n", path.toAbsolutePath());

      if (Files.isDirectory(path)) // output directory listing
      {
         System.out.printf("%nDirectory contents:%n");
         
         // object for iterating through a directory's contents
         DirectoryStream<Path> directoryStream = 
            Files.newDirectoryStream(path);

         for (Path p : directoryStream)
            System.out.println(p);
      } 
   } 
   else // not file or directory, output error message
   {
      System.out.printf("%s does not exist%n", path);
   }   
}
 
開發者ID:cleitonferreira,項目名稱:LivroJavaComoProgramar10Edicao,代碼行數:41,代碼來源:FileAndDirectoryInfo.java

示例11: loadDataFilesList

import java.nio.file.Files; //導入方法依賴的package包/類
public static List<String> loadDataFilesList(String prefix, Path bwcIndicesPath) throws IOException {
    List<String> indexes = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(bwcIndicesPath, prefix + "-*.zip")) {
        for (Path path : stream) {
            indexes.add(path.getFileName().toString());
        }
    }
    Collections.sort(indexes);
    return indexes;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:11,代碼來源:OldIndexUtils.java

示例12: installConfig

import java.nio.file.Files; //導入方法依賴的package包/類
/**
 * Copies the files from {@code tmpConfigDir} into {@code destConfigDir}.
 * Any files existing in both the source and destination will be skipped.
 */
private void installConfig(PluginInfo info, Path tmpConfigDir, Path destConfigDir) throws Exception {
    if (Files.isDirectory(tmpConfigDir) == false) {
        throw new UserException(ExitCodes.IO_ERROR, "config in plugin " + info.getName() + " is not a directory");
    }

    Files.createDirectories(destConfigDir);
    setFileAttributes(destConfigDir, CONFIG_DIR_PERMS);
    final PosixFileAttributeView destConfigDirAttributesView =
        Files.getFileAttributeView(destConfigDir.getParent(), PosixFileAttributeView.class);
    final PosixFileAttributes destConfigDirAttributes =
        destConfigDirAttributesView != null ? destConfigDirAttributesView.readAttributes() : null;
    if (destConfigDirAttributes != null) {
        setOwnerGroup(destConfigDir, destConfigDirAttributes);
    }

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(tmpConfigDir)) {
        for (Path srcFile : stream) {
            if (Files.isDirectory(srcFile)) {
                throw new UserException(ExitCodes.DATA_ERROR, "Directories not allowed in config dir for plugin " + info.getName());
            }

            Path destFile = destConfigDir.resolve(tmpConfigDir.relativize(srcFile));
            if (Files.exists(destFile) == false) {
                Files.copy(srcFile, destFile);
                setFileAttributes(destFile, CONFIG_FILES_PERMS);
                if (destConfigDirAttributes != null) {
                    setOwnerGroup(destFile, destConfigDirAttributes);
                }
            }
        }
    }
    IOUtils.rm(tmpConfigDir); // clean up what we just copied
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:38,代碼來源:InstallPluginCommand.java

示例13: assertInstallCleaned

import java.nio.file.Files; //導入方法依賴的package包/類
void assertInstallCleaned(Environment env) throws IOException {
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(env.pluginsFile())) {
        for (Path file : stream) {
            if (file.getFileName().toString().startsWith(".installing")) {
                fail("Installation dir still exists, " + file);
            }
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:10,代碼來源:InstallPluginCommandTests.java

示例14: getModuleBundles

import java.nio.file.Files; //導入方法依賴的package包/類
static List<Bundle> getModuleBundles(Path modulesDirectory) throws IOException {
    // damn leniency
    if (Files.notExists(modulesDirectory)) {
        return Collections.emptyList();
    }
    List<Bundle> bundles = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(modulesDirectory)) {
        for (Path module : stream) {
            if (FileSystemUtils.isHidden(module)) {
                continue; // skip over .DS_Store etc
            }
            PluginInfo info = PluginInfo.readFromProperties(module);
            if (!info.isJvm()) {
                throw new IllegalStateException("modules must be jvm plugins: " + info);
            }
            if (!info.isIsolated()) {
                throw new IllegalStateException("modules must be isolated: " + info);
            }
            Bundle bundle = new Bundle();
            bundle.plugins.add(info);
            // gather urls for jar files
            try (DirectoryStream<Path> jarStream = Files.newDirectoryStream(module, "*.jar")) {
                for (Path jar : jarStream) {
                    // normalize with toRealPath to get symlinks out of our hair
                    bundle.urls.add(jar.toRealPath().toUri().toURL());
                }
            }
            bundles.add(bundle);
        }
    }
    return bundles;
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:33,代碼來源:PluginsService.java

示例15: scan

import java.nio.file.Files; //導入方法依賴的package包/類
void scan(Path p) throws IOException {
    if (Files.isDirectory(p)) {
        for (Path c: Files.newDirectoryStream(p)) {
            scan(c);
        }
    } else if (isTidyFile(p)) {
        scan(Files.readAllLines(p, Charset.defaultCharset()));
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:10,代碼來源:Main.java


注:本文中的java.nio.file.Files.newDirectoryStream方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。