java nio Files.newDirectoryStream用法

try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(Paths.get(directory,"*.ts"))){

            byte[] buff = Files.readAllBytes(Paths.get(m3u8File));

            String playList = new String(buff);

            int cntTSFiles = Iterators.size(dirStream.iterator());

            HashMap<String, Object> memMapping = Maps.newHashMapWithExpectedSize(cntTSFiles + 2);

            //播放清单
            memMapping.put("playlist",playList);
            //把原始文件放进去,方便以后下载
            memMapping.put("binary",Base64.getEncoder().encodeToString(Files.readAllBytes(Paths.get(originalWavFile))));

            Iterator<Path> iterator = dirStream.iterator();
            while (iterator.hasNext()) {
                Path path = iterator.next();
                String binary = Base64.getEncoder().encodeToString(Files.readAllBytes(path));
                String tsFile = path.getFileName().toString();
                memMapping.put(tsFile,binary);
            }

            String mediaId = String.format("media.%s",uuid);
            //切片以后的文件添加到缓存
            cacheService.setCacheMap(mediaId, memMapping);

            //一周以后失效
            cacheService.expire(mediaId,7, TimeUnit.DAYS);

        }catch (IOException ex)
        {
            log.error("读取MPEG-2 TS文件失败:{}",ex);
        }

网络代码:

private List<IOException> tryRemoveDirectoryContents(@Nonnull Path path) {
  Path normalized = path.normalize();
  List<IOException> accumulatedErrors = new ArrayList<>();
  if (!Files.isDirectory(normalized)) return accumulatedErrors;
  try (DirectoryStream<Path> children = Files.newDirectoryStream(normalized)) {
    for (Path child : children) {
      accumulatedErrors.addAll(tryRemoveRecursive(child));
    }
  } catch (IOException e) {
    accumulatedErrors.add(e);
  }
  return accumulatedErrors;
}
 public static void main(String... args) throws IOException {
        String pathString = System.getProperty("java.io.tmpdir");
        Path path = Paths.get(pathString);
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
            Iterator<Path> iterator = ds.iterator();
            int c = 0;
            while (iterator.hasNext() && c < 5) {
                Path p = iterator.next();
                System.out.println(p);
                c++;
            }
        }
    }
 public static void main(String... args) throws IOException {
        String pathString = System.getProperty("java.io.tmpdir");
        Path path = Paths.get(pathString);
        System.out.println("Path to stream: " + path);
        //stream all files with name ending .log
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(path,
                p -> p.getFileName().toString().startsWith("aria"))) {
            ds.forEach(System.out::println);
        }
    }
 private static DirectoryStream<Path> list(Path dir) throws IOException {
  return Files.newDirectoryStream(dir, entry -> !DirectoryLock.LOCK_FILE_NAME.equals(entry.getFileName().toString()));
 }
private void forEachTopologyDistDir(ConsumePathAndId consumer) throws IOException {
  Path stormCodeRoot = Paths.get(ConfigUtils.supervisorStormDistRoot(conf));
  if (Files.exists(stormCodeRoot) && Files.isDirectory(stormCodeRoot)) {
    try (DirectoryStream<Path> children = Files.newDirectoryStream(stormCodeRoot)) {
      for (Path child : children) {
        if (Files.isDirectory(child)) {
          String topologyId = child.getFileName().toString();
          consumer.accept(child, topologyId);
        }
      }
    }
  }
}
/**
 * 复制目录
 */
public static void copyDir(@NotNull Path from, @NotNull Path to) throws IOException {
  Validate.isTrue(isDirExists(from), "%s is not exist or not a dir", from);
  Validate.notNull(to);
  makesureDirExists(to);
  try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(from)) {
    for (Path path : dirStream) {
      copy(path, to.resolve(path.getFileName()));
    }
  }
}
private void copyRecursively( Path source, Path target ) throws IOException
{
  try ( DirectoryStream<Path> directoryStream = Files.newDirectoryStream( source ) )
  {
    for ( Path sourcePath : directoryStream )
    {
      Path targetPath = target.resolve( sourcePath.getFileName() );
      if ( Files.isDirectory( sourcePath ) )
      {
        Files.createDirectories( targetPath );
        copyRecursively( sourcePath, targetPath );
      }
      else
      {
        Files.copy( sourcePath, targetPath,
            REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES );
      }
    }
  }
}

代码来源:https://www.logicbig.com/how-to/code-snippets/jcode-java-io-files-newdirectorystream.html

https://www.codota.com/code/java/methods/java.nio.file.Files/newDirectoryStream

原文地址:https://www.cnblogs.com/passedbylove/p/11773357.html