我有一个包含多个文件的目录。我需要使用Java只检索List中的XML文件名。我怎么能做到这一点?
答案 0 :(得分:4)
试试这个[FilePath是目录路径!!]
public static void main(String[] args) {
File folder = new File("{FilePath}");
File[] listOfFiles = folder.listFiles();
for(int i = 0; i < listOfFiles.length; i++){
String filename = listOfFiles[i].getName();
if(filename.endsWith(".xml")||filename.endsWith(".XML"))
{
System.out.println(filename);
}
}
}
}
答案 1 :(得分:1)
您也可以使用FilenameFilter:
import java.io.File;
import java.io.FilenameFilter;
public class FileDemo implements FilenameFilter {
String str;
// constructor takes string argument
public FileDemo(String ext) {
str = "." + ext;
}
// main method
public static void main(String[] args) {
File f = null;
String[] paths;
try {
// create new file
f = new File("c:/test");
// create new filter
FilenameFilter filter = new FileDemo("xml");
// array of files and directory
paths = f.list(filter);
// for each name in the path array
for (String path : paths) {
// prints filename and directory name
System.out.println(path);
}
} catch (Exception e) {
// if any error occurs
e.printStackTrace();
}
}
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(str.toLowerCase());
}
}
答案 2 :(得分:0)
您可以使用File.filter(FileNameFilter)进行过滤。提供FileNameFilter的实现
答案 3 :(得分:0)
File f = new File("C:\\");
if (f.isDirectory()){
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if(name.endsWith(".xml")){
return true;
}
return false;
}
};
if (f.list(filter).length > 0){
/* Do Something */
}
}