獲取指定目錄(包含子目錄)下所有的txt檔案的個數,並列印檔名稱。程式2。
阿新 • • 發佈:2019-01-31
public class try2 {
public static void main(String[] args) {
File f=new File("G:\\avi");
List<String> l = new ArrayList<>();//新建了一個list用來放結果
l= readFile(f);
System.out.println(l);
System.out.println(l.size());
}
private static List readFile(File file) { //方法的返回值是一個list
List<String> result = new ArrayList<>(); //新建list列表
for (String s : file.list()) { //list()返回一個字串陣列,這些字串指定此抽象路徑名錶示的目錄中的檔案和目錄。
File child = new File(file.getAbsolutePath() + "/" + s);//新建了一個File檔案child來存入檔案路徑和檔名
if (child.isDirectory()) { //判斷這個File是否是資料夾
result.addAll(readFile(child)); //是資料夾就再呼叫該方法,並把其返回的結果放入result
} else result.add(child.getAbsolutePath()); //File是檔案,將其地址放入result
}
return result;
}
public static void main(String[] args) {
File f=new File("G:\\avi");
List<String> l = new ArrayList<>();//新建了一個list用來放結果
l= readFile(f);
System.out.println(l);
System.out.println(l.size());
}
private static List readFile(File file) { //方法的返回值是一個list
List<String> result = new ArrayList<>(); //新建list列表
for (String s : file.list()) { //list()返回一個字串陣列,這些字串指定此抽象路徑名錶示的目錄中的檔案和目錄。
File child = new File(file.getAbsolutePath() + "/" + s);//新建了一個File檔案child來存入檔案路徑和檔名
if (child.isDirectory()) { //判斷這個File是否是資料夾
result.addAll(readFile(child)); //是資料夾就再呼叫該方法,並把其返回的結果放入result
} else result.add(child.getAbsolutePath()); //File是檔案,將其地址放入result
}
return result;
}