标签:code style main accept 文件 dir director ISE nbsp
首先遍历来一下,这里分为递归与不递归的两种操作:
非递归操作
//非递归复用了 LinkedList private static void NotRecursive() { LinkedList<File> list=new LinkedList<>(); int folderNum=0; int fileNum=0; File file=new File("E:/动脑"); if(file.exists()){ File[] fs=file.listFiles(); for(File f1:fs){ if(f1.isDirectory()){ folderNum++; list.add(f1); // System.out.println("Folder Name:"+f1.getName()); }else{ fileNum++; System.out.println("File Name:"+f1.getName()); } } File f2; while(!list.isEmpty()){ f2=list.removeFirst(); fs=f2.listFiles(); for(File f1:fs){ if(f1.isDirectory()){ folderNum++; list.add(f1); // System.out.println("Folder Name:"+f1.getName()); }else{ fileNum++; System.out.println("File Name:"+f1.getName()); } } } }else{ System.out.println("非文件目录"); } System.out.println("FileNum: "+fileNum+" FolderNum: "+folderNum); }
递归操作:并筛选出MP3格式的文件
private static LinkedList<File> Recursive(String path) {
LinkedList<File> list=new LinkedList<>();
File file=new File(path);
if(file.exists()){
File[] fs =file.listFiles();
for(File f1:fs){
if(f1.isDirectory()){
Recursive(f1.getAbsolutePath());
}else{
if(f1.getName().endsWith("mp3"))
list.add(f1);
System.out.println("File Name:"+f1.getName());
}
}
}else{
}
return list;
}
public class DirList { public static void main(String[] args) { String path="E:/动脑"; File file=new File(path); String[] fs=file.list(new FilenameFilter() { private String tag=".mp3"; @Override public boolean accept(File dir, String name) { return name.endsWith(tag); } }); long l=0; Arrays.sort(fs); for(String s1:fs){ System.out.println(s1); l+=new File("E:/动脑/"+s1).length(); } System.out.println(l/1024/1024); } }
标签:code style main accept 文件 dir director ISE nbsp
原文地址:https://www.cnblogs.com/zzl521/p/8987358.html