java 列出目录结构
发布网友
发布时间:2022-05-06 15:21
我来回答
共3个回答
热心网友
时间:2022-07-01 04:43
public class DirectoryPrinter {
private static List<String> list = new ArrayList<String>();
private static int floor = 0;
public static void printDirectory(File root) {
if (root.isFile()) {
System.out.println(getPreString(floor, root) + root.getName());
} else {
System.out.println(getPreString(floor, root) + root.getName());
floor++;
File[] files = root.listFiles();
setLast(files);
for (File file : files) {
printDirectory(file);
}
floor--;
}
}
private static String getPreString(int floor, File file) {
if (floor == 0)
return "";
String preString = "ㄴ";
for (int i = 1; i < floor; i++) {
file = file.getParentFile();
if (list.contains((file.getAbsolutePath() + file.getName())))
preString = " " + preString;
else
preString = "|" + preString;
}
return preString;
}
private static void setLast(File[] files) {
if (files.length != 0) {
int last = 0;
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
last = i;
}
list.add(files[last].getAbsolutePath() + files[last].getName());
}
}
public static void main(String[] args) {
DirectoryPrinter.printDirectory(new File("D://workspace//JavaTest"));
}
}
热心网友
时间:2022-07-01 04:44
import java.io.File;
public class ShowAllFiles {
public static void main(String[] args) {
PrintFiles.getInstance("D:\\svn\\dgepb\\source\\web\\fs\\js");
}
}
class PrintFiles{
private File file;
private int files=0;
private PrintFiles(String file){
this.file=new File(file);
print(this.file);
System.out.println("共有文件数:"+files);
}
public static PrintFiles getInstance(String file){
return new PrintFiles(file);
}
void print(File f){
if(f.isDirectory()){
File files[]=f.listFiles();
for(int i=0;i<files.length;i++){
print(files[i]);
}
}else if(f.isFile()){
System.out.println(f.getAbsolutePath());
files++;
}else{
System.out.println(f.getAbsolutePath()+" 不是一个有效的文件路径!");
}
}
}
热心网友
时间:2022-07-01 04:44
递归遍历或者非递归遍历,网上好多