【Java-使用walkFileTree工具类深度遍历查找文件】

例子: 

public class Test {
	public static void main(String[] args) {
		// 查找指定盘下的所有音乐文件
		HashMap<String, File> mp3FileMap = readMp3Files();
		for (Entry<String, File> entry : mp3FileMap.entrySet()) {
			System.out.printf("音乐名称:%s\t", entry.getKey());
			System.out.printf("音乐文件路径:%s\t", entry.getValue().getPath());
		}
	}

	public static HashMap<String, File> readMp3Files() {
		File dir = new File("D:\\实验作业论文等");
		// 保存查找到的mp3文件
		ArrayList<File> mp3FileList = new ArrayList<File>();

		try {
			Files.walkFileTree(dir.toPath(), new SimpleFileVisitor<Path>() {
				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
					if(file.toFile().getName().endsWith(".mp3")) {
						mp3FileList.add(file.toFile());
					}
					return FileVisitResult.CONTINUE;
				}	
				//访问文件错误,继续访问
				@Override
				public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
					// TODO Auto-generated method stub
					return FileVisitResult.CONTINUE;
				}
			});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 遍历File数组,重新保存Map中
		HashMap<String, File> fileMap = new LinkedHashMap<String, File>();
		for (File f : mp3FileList) {
			String fileName = f.getName();
			String key = fileName.substring(0, fileName.indexOf("."));
			fileMap.put(key, f);
		}
		return fileMap;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值