![](/img/trans.png)
[英]What is the most efficient way to list all of the files in a directory (including sub-directories)?
[英]How to list all files within a directory and all its sub-directories
我制作了一個程序,該程序列出了擴展名所需目錄中的所有文件名。 現在,我想要並且不知道如何更改它,以便也列出子目錄中的所有文件。 你有什么想法? 這是我的代碼。 謝謝!
import java.util.*;
import java.io.*;
public class Program {
public static void main(String str[]){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("1.Enter directory name:");
String adress = br.readLine();
System.out.println("2.Enter file extension:");
String exten = br.readLine();
File directory = new File(adress);
File[] f = directory.listFiles();
List<String> files = new ArrayList<String>();
List<String> valid = new ArrayList<String>();
List<String> names = new ArrayList<String>();
for(int i=0; i < f.length; i++){
if(f[i].isFile()){
files.add(f[i].getName());
}
}
for(int i=0; i < files.size(); i++){
if (files.get(i).endsWith(exten)){
valid.add(files.get(i));
}
}
for(int i=0; i < valid.size(); i++){
int pos = valid.get(i).lastIndexOf(".");
names.add(valid.get(i).substring(0, pos));
System.out.println(names.get(i));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
如果可以使用Java 7或8,則可以使用FileVisitor ,但是在Java 7中,這意味着要編寫多行代碼。 如果不是,並且您想保持簡單,則Apache Commons FileUtils可能是您的朋友。
Collection<File> files = FileUtils.listFiles(path, new String[]{"xlxs"}, true);
我花了一會兒時間在目錄中找到所有* .xls或* .xlsx。
希望這對您的問題有所幫助。
public static List<String> fileSearch(String d){
List<String> filesFound = new ArrayList<String>();
File dir = new File(d);
try{
for(File file: dir.listFiles()){
if(file.isFile() && (file.getName().toLowerCase().endsWith(".xlsx") || file.getName().toLowerCase().endsWith(".xls"))){
long filesize = file.length();
long fileSize = filesize / 1024;
filesFound.add(d + "\\" + file.getName());
System.out.println("Added: " + d + "\\" + file.getName() + " " + fileSize + " KB" );
}else if(file.isDirectory() && !file.isHidden()){
System.out.println("Found Directory: " + file.getName());
filesFound.addAll(fileSearch(d + "\\" + file.getName()));
}else if(isRoot(file)){
//DO NOTHING
}
}
}catch(NullPointerException ex){
ex.printStackTrace();
}finally{
return filesFound;
}
}
private static boolean isRoot(File file){
File[] roots = File.listRoots();
for (File root : roots) {
if (file.equals(root)) {
return true;
}
}
return false;
}
這樣,它將在每個文件中搜索一個匹配項,如果匹配,則將其添加到數組“ filesFound”中,您可以獲取所有匹配文件的路徑。 但對於您來說,您將取出.xlsx和.xls部分並添加您的ext。
fileSearch(String d, String ext)
並將if then更改為:
if(file.isFile() && file.getName().toLowerCase().endsWith(ext))
我也有輸出,無論何時找到與它旁邊的文件大小匹配的文件。 文件大小只是視覺上的幫助,並不包含在數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.