public void traverseFolder2(String path) {
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (null == files || files.length == 0) {
System.out.println("文件夹是空的!");
return;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夹:" + file2.getAbsolutePath());
traverseFolder2(file2.getAbsolutePath());
} else {
System.out.println("文件:" + file2.getAbsolutePath());
}
}
}
} else {
System.out.println("文件不存在!");
}
}
扩展资料
public void traverseFolder1(String path) {
int fileNum = 0, folderNum = 0;
File file = new File(path);
if (file.exists()) {
LinkedList<File> list = new LinkedList<File>();
File[] files = file.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夹:" + file2.getAbsolutePath());
list.add(file2);
foldeNum++;
} else {
System.out.println("文件:" + file2.getAbsolutePath());
fileNum++;
}
}
File temp_file;
while (!list.isEmpty()) {
temp_file = list.removeFirst();
files = temp_file.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夹:" + file2.getAbsolutePath());
list.add(file2);
folderNum++;
} else {
System.out.println("文件:" + file2.getAbsolutePath());
fileNum++;
}
}
}
} else {
System.out.println("文件不存在!");
}
System.out.println("文件夹共有:" + folderNum + ",文件共有:" + fileNum);
}
参考资料:百度百科 Java
public class Test {
public static void main(String[] args) throws Exception {
//递归显示C盘下所有文件夹及其中文件
File root = new File("c:");
showAllFiles(root);
}
final static void showAllFiles(File dir) throws Exception{
File[] fs = dir.listFiles();
for(int i=0; i<fs.length; i++){
System.out.println(fs[i].getAbsolutePath());
if(fs[i].isDirectory()){
try{
showAllFiles(fs[i]);
}catch(Exception e){}
}
}
}
}
public static void main(String[] args) {
refreshFileList("c:\\java");
}
public static void refreshFileList(String strPath) {
File dir = new File(strPath);
File[] files = dir.listFiles();
if (files == null)
return;
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
refreshFileList(files[i].getAbsolutePath());
} else {
String strFileName = files[i].getAbsolutePath().toLowerCase();
System.out.println("---"+strFileName);
filelist.add(files[i].getAbsolutePath());
}
}
}
}