[英]Program To print specific path of folder into its next sub folder in java
[英]find specific file type from folder and its sub folder
我正在編寫一個方法來從文件夾和子文件夾中獲取特定文件類型,如pdf或txt,但我不能解決這個問題。 這是我的代碼
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
我當前的方法列出所有文件,但我需要特定的文件
對於不需要通過子目錄遞歸的篩選列表,您可以這樣做:
directory.listFiles(new FilenameFilter() {
boolean accept(File dir, String name) {
return name.endsWith(".pdf");
}});
為了提高效率,您可以提前創建FilenameFilter而不是每次調用。
在這種情況下,因為您還要掃描子文件夾,所以無需過濾文件,因為您仍需要檢查子文件夾。 事實上你幾乎就在那里:
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
if (file.getName().endsWith(".pdf")) {
System.out.println(file.getAbsolutePath());
}
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
if(file.getName().endsWith(".pdf")) {
//it is a .pdf file!
}
/ * ** /
嘗試在函數http://docs.oracle.com/javase/6/docs/api/java/io/FilenameFilter.html中使用FilenameFilter接口
http://www.mkyong.com/java/how-to-find-files-with-certain-extension-only/ - 用於具有擴展過濾器的代碼
使用File.listFiles(FileFilter) 。
例:
File[] fList = directory.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().endSwith(".pdf");
}
});
您可以使用apache fileUtils類
String[] exte= {"xml","properties"};
Collection<File> files = FileUtils.listFiles(new File("d:\\workspace"), exte, true);
for(File file: files){
System.out.println(file.getAbsolutePath());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.