Java 编程题 查开磁盘目录树结构

package com.et.test;

import java.io.File;
/*
 *  模拟
 *  MorceSoft Dos命令tree
 * F:.
 *	├─Downloads
 *	├─Favorites
 *	│  └─Links
 *			├─one.txt
 *			├─two.txt
 *  │		└─three.txt
 *	├─Links
 *	├─Music
 *	├─Pictures
 *	├─Saved Games
 *	├─Searches
 *	└─Videos
 */
public class FileDirectory {
	public static void main(String[] args) {
		File file = new File("D:");
		//文件对象实际存在,并且是目录,递归方法清晰的显示包含的所有文件、目录
		if(file.exists()) {
			getDeptTree(file,"");
		}
	}
	protected static void getDeptTree(File f, String prefix) {
		if(f.listFiles() != null){
			//获取目录下的所有文件和子目录
			File[] childs = f.listFiles();
			//遍历file数组
			for (int i = 0; i < childs.length;i++) {
				String strLine = "";
				String strStart = "";
				if (childs.length - i > 1) {
					strStart = prefix + "  │";
				} else {
					strStart = prefix + "  ";
				}
				if (i == childs.length - 1) {
					strLine = prefix + "  └─";
				} else {
					strLine = prefix + "  ├─";
				}
				//如果是文件,打印文件名及大小
				if(childs[i].isFile()) {
					System.out.println(strLine + childs[i].getName()+"  "+childs[i].length()+"B");
				}
				//如果是目录,打印目录名,执行递归方法
				if (childs[i].isDirectory()) {
					System.out.println(strLine + childs[i].getName());
					getDeptTree(childs[i], strStart);
				}
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值