用java写一个代码实现: 如何列出某个目录下的所有子目录

只要求列出目录,不能列出文件
2024-12-12 14:18:31
推荐回答(4个)
回答1:

/**
* 列出文件夹下的子文件夹名
* @param localRoot
* @throws content
*/
public static void list(String localRoot) throws Exception {
File[] fs = new File(localRoot).listFiles();
if ((fs == null) || (fs.length <= 0)) {
System.out.println("空文件夹");
return;
}
for (File f : fs) {
if (f.isDirectory()) {
System.out.println("目录:"+ f.getName());
}
}
}

建立个class然后见个main方法调用一下就可以了!

回答2:

import java.io.*;
public class Test
{
static void myList(String s)
{
File f=new File(s);
String[] m=null;
m=f.list();
for(int i=0;i {
File fm=new File(s+"/"+m[i]);
if(!fm.isFile())
{
System.out.println (fm.getName());
myList(s+"/"+m[i]);
}
}
}
public static void main (String[] args) {
myList("a");//假设你的目录名是a 你可以换成别的

}
}

回答3:

递归调用就行了嘛
public class Test {
public static void find(String filePath) {
File file = new File(filePath);
if (file.isDirectory()) {
System.out.println(file.getPath());
File[] listFiles = file.listFiles();
if (listFiles != null) {
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i].isDirectory()) {
Test.find(listFiles[i].getPath());
}
}
}
}
}

public static void main(String[] args) {
find("c:");
}
}

回答4:

//:ListDirectories.java
import java.io.File;
import java.io.FileFilter;
public class ListDirectories {
//File filter object.
private static FileFilter filter = new MyFilter();
public static void main(String[] args) {
String dir = javax.swing.JOptionPane.showInputDialog("Input root dir here:");
if(dir!=null)
printRecursive(dir);
}

private static void printRecursive(String dir) {
File df = new File(dir);
if(df.isDirectory() && df.canRead())
printRecursive(df);
else
System.out.println("Directory '"+dir+"' is not exists or can not be read.");
}

private static void printRecursive(File dir){
File[] files = dir.listFiles(filter);
if(files!=null)
for(int i=0; i System.out.println(files[i].getAbsolutePath());
if(files[i].canRead()){
printRecursive(files[i]);
}
}
}
//File filter
private static class MyFilter implements FileFilter{
public boolean accept(File pathname) {
return pathname.isDirectory();
}
}
}