Java以树形结构在控制台中打印某文件夹下的子文件夹和文件的名称

采蘑菇的小日天 2018-08-15 09:01:23
在控制台的输出是这样,如何在递归里实现这个分级打印,求大佬解答,最好附上代码,求!!!!
我的文件夹
|
------------------文件夹A
| |
| -------------------------文件1
| |
| -------------------------文件2
|
-------------------文件夹B
|
-------------------------文件3
...全文
252 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
verejava 2018-08-15
  • 打赏
  • 举报
回复
设计模式 之 组合模式 应用

http://www.verejava.com/?id=17175159089150
吸尘器 2018-08-15
  • 打赏
  • 举报
回复
简单写了一个,参考一下把!

public class FolderTreeTest {

/**
* @param args
*/
public static void main(String[] args) {
String rootFolderPath = "D:\\ROOT_FOLDER";
FolderTreeTest.showTree(0,new File(rootFolderPath));
}

public static void showTree(int level,File parentFolderPath){
if(parentFolderPath.isDirectory()){
File[] childFiles = parentFolderPath.listFiles();
for(File file : childFiles){
showNameByLevel(level);
System.out.println(file.getName());
if(file.isDirectory()){
FolderTreeTest.showTree(level + 1,file);
}
}
}
}
public static void showNameByLevel(int level){
StringBuffer spaceStr = new StringBuffer();
if(level > 0){
for(int i = 0 ; i < level ; i ++){
spaceStr.append(" ");
}
}
if(spaceStr.length() > 0)System.out.print("|" + spaceStr);
System.out.println("|");
if(spaceStr.length() > 0)System.out.print("|" + spaceStr);
System.out.print("----");
}
}

效果如图
  • 打赏
  • 举报
回复
公司要求递归直接打出来,在递归的方法里使用判断语句说不行…………
醉酒后的李白 2018-08-15
  • 打赏
  • 举报
回复
可以一行一行来输出,遇到每个层级,取出对应的名称。

51,402

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧