A-A+
文件夹目录的循环遍历
主要是对文件夹文件的循环遍历,利用了递归,以及文件与文件夹的判断,从而打印出文件夹内的所有结构。
掌握文件夹基本操作以及对递归的掌握。
不说了,先上代码:
主要是对文件夹文件的循环遍历,利用了递归,以及文件与文件夹的判断,从而打印出文件夹内的所有结构。掌握文件夹基本操作以及对递归的掌握。
不说了,先上代码:
import java.io.*;
public class FolderDir {
static long AllByte = 0;
static void Dir(String path1) {
try {
File file = new File(path1);// 上层目录
// System.out.println(path1);
String list[] = file.list();
// 遍历循环所有文件名称
for (String string : list) {
printBlank(file.getPath());
System.out.println("|"+string);
File newfile = new File(file.getPath() + "\" + string);// 下一层目录
if (newfile.isDirectory()) { //
Dir(newfile.getPath());
} else {
FileInputStream fis = new FileInputStream(newfile);
AllByte = AllByte + fis.available();
fis.close(); // 关闭输入流
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
static void printBlank(String path2) { // 根据其地址的长度计算出应该要打印空格的长度
for (int i = 0; i < path2.length(); i++) {
System.out.print(" ");
}
}
public static void main(String[] args) {
String path = "D:\Program Files";//所要遍历的文件夹
System.out.println(path);
Dir(path);
System.out.println("文件夹" + path.substring(path.lastIndexOf("\") + 1)
+ "大小为:" + AllByte + "字节");
}
}

