如何在java中打开以特定前缀开头的所有文件?
在Java中,有没有办法打开以特定名称开头的目录中的一些文本文件 例如,在我的目录中,我有以下文件:如何在java中打开以特定前缀开头的所有文件?,java,file,Java,File,在Java中,有没有办法打开以特定名称开头的目录中的一些文本文件 例如,在我的目录中,我有以下文件: Ab-01.txt Ab-02.txt Ab-03.txt Ab-04.txt SomethingElse.txt NotRelated.txt 所以现在在我的Java代码中,我只想打开那些以“Ab-”开头的文件 在父文件夹上使用此方法并实现FilenameFilter,如: boolean accept(File dir, String name){ return name.mat
Ab-01.txt
Ab-02.txt
Ab-03.txt
Ab-04.txt
SomethingElse.txt
NotRelated.txt
所以现在在我的Java代码中,我只想打开那些以“Ab-
”开头的文件
在父文件夹上使用此方法并实现FilenameFilter,如:
boolean accept(File dir, String name){
return name.matches("AB-\n{2}.*")
}
布尔接受(文件目录,字符串名称){
返回name.matches(“AB-\n{2}.*”)
}
没有神奇的方法。你应该列出目录中的所有文件,检查名称,并按照模式读取文件。然后递归检查每个目录。是。使用: 例如:
File dir = new File("/path/to/directory");
File[] foundFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("Ab-");
}
});
for (File file : foundFiles) {
// Process file
}
当然,将
accept()
方法中的条件更改为您需要的任何条件。因此,可能name.startsWith(“Ab-”)&&name.endsWith(“.txt”)
创建一个表示目录的java.io.File,然后使用带a的。您可以准确地告诉它您想要匹配的模式,例如name.startsWith(“Ab-”)
应该可以哇,它也可以在java6上工作(我在google上写了'File java',1.4是第一个结果:p)我讨厌google有时把1.4文档放在结果中比1.6文档高的位置。google
File javadoc 6
似乎是最好的选择。你会想要包括一个空检查,比如for(File File:Objects.requirennoull)(foundFiles)){…
File files[] = directory.listFiles();
for (File f : files) {
if(//filename matches what you want)
{
// do whatever you want with each File f
}
}