有没有办法在Java中以特定名称开头的目录中打开一些文本文件?
例如,在我的目录中,我有以下文件:
Ab-01.txt
Ab-02.txt
Ab-03.txt
Ab-04.txt
SomethingElse.txt
NotRelated.txt
Run Code Online (Sandbox Code Playgroud)
所以现在在我的Java代码中我只想打开那些以" Ab-
" 开头的文件
Ada*_*kin 39
是.用途File.listFiles(FilenameFilter)
:
举个例子:
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
}
Run Code Online (Sandbox Code Playgroud)
当然,将accept()
方法中的条件更改为您需要的任何条件.也许吧name.startsWith("Ab-") && name.endsWith(".txt")
.
http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#listFiles(java.io.FilenameFilter)在父文件夹上使用此方法,并实现FilenameFilter,如:
boolean accept(File dir, String name){ return name.matches("AB-\n{2}.*") }
归档时间: |
|
查看次数: |
19804 次 |
最近记录: |