我试图读取文件夹的文件名并将它们保存在数组列表中,但是我在我不想要的数组中得到了不可见的文件名(实际上我只想保存.txt文件名)。有谁知道在创建列表之前先在代码中进行更改吗?
String pathLevel= "/Users/MaxRuizTagle/Desktop/lvl/"; File file = new File(pathLevel); String [] levelNames = file.list(); String [] matrix= new String[levelNames.length];
使用java.nio.file。使用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());
如果你的Java 7中,执行等效采用Files.newDirectoryStream():
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());