例子:
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;
}
}