I have a directory with multiple files. I need to retrieve only XML file names in a List using Java. How can I accomplish this?
Asked
Active
Viewed 1.5k times
1
-
1Can you please show what you have tried. Some code please. – A Paul Dec 13 '13 at 11:24
-
1See this : http://stackoverflow.com/questions/5751335/using-file-listfiles-with-filenameextensionfilter – Nishan Dec 13 '13 at 11:27
4 Answers
5
Try this, {FilePath} is directory path:
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) `filename.endsWith(".xml")` will miss any file ending .XML. 2) Use a `FilenameFilter`! – Andrew Thompson Dec 13 '13 at 13:31
-
@AndrewThompson: jus add an Or statement to if statement it works fine..!! – BlackPOP Dec 13 '13 at 14:34
-
*"jus add an Or statement to if statement it will work fine..!!"* I don't *have to do* anything. OTOH since you changed that part, I'll remove the down-vote. ***It would still be more optimal to use the defined API for it though.*** – Andrew Thompson Dec 13 '13 at 14:37
1
You can use also a 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());
}
}

Stephan
- 41,764
- 65
- 238
- 329
-
I would change `name.endsWith(str)` to `name.toLowerCase().endsWith(str.toLowerCase())` in order to account for ..different case between what is specified, and what is found. Otherwise, +1 not only for the correct API, but an example. Nice. :) – Andrew Thompson Dec 13 '13 at 13:33
0
You can filter by using File.filter(FileNameFilter). Provide your implementation for FileNameFilter

Dragon
- 193
- 1
- 3
- 7
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 */
}
}

user3548196
- 355
- 1
- 9
- 32