Read only visibles directory´s file names

后端 未结 1 1546
说谎
说谎 2021-01-29 02:45

Im trying to read the filenames of a folder an save them in an array list, but i get invisble files names in my array that i dont want(actually i want only to saves the .txt fil

相关标签:
1条回答
  • 2021-01-29 02:56

    Use java.nio.file. Using Java 8:

    final Path dir = Paths.get("/Users/MaxRuizTagle/Desktop/lvl/");
    
    final List<String> textFiles = Files.list(dir)
        .filter(path -> !Files.isHidden(path))
        .map(path -> path.getFileName().toString())
        .filter(s -> s.endsWith(".txt"))
        .collect(Collectors.toList());
    

    If Java 7, do the equivalent with Files.newDirectoryStream():

    final Path dir = Paths.get("/Users/MaxRuizTagle/Desktop/lvl/");
    
    final DirectoryStream<Path> dirstream
        = Files.newDirectoryStream(dir, "*.txt");
    
    final List<String> textFiles = new ArrayList<>();
    
    for (final Path entry: dirstream)
        if (!Files.isHidden(entry))
            textFiles.add(entry.getFileName().toString());
    
    0 讨论(0)
提交回复
热议问题