项目要求
a)读取指定目录的所有mp3文件,包括所有子目录
b)将所读取的文件呈现在控制台
代码如下
import java.io.*;
import java.util.Scanner;
public class fileMP3 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please enter the directory to search: ");
String songPath = input.next();
File songFile = new File(songPath);
System.out.println("\nFind the MP3 files in the specified directory("
+ songPath + "): ");
findMP3(songFile, songPath);
System.out.println("----Find end----");
}
private static void findMP3(File songFile, String songPath) {
File[] songList = songFile.listFiles();
if (songList != null) {
for (File s : songList) {
// 用递归法来查找各个子目录
if (s.isDirectory() == true) {
findMP3(s, s.getAbsolutePath());
} else {
// String类下的endsWith来判断文件后缀
if (s.getAbsolutePath().endsWith(".mp3") == true
|| s.getAbsolutePath().endsWith("MP3")) {
System.out.println(s.getAbsolutePath());
}
}
}
}
}
}
文件截图
运行结果
Please enter the directory to search:
src
Find the MP3 files in the specified directory(src):
D:\eclipse\workspace\homework\src\Tynisha Keli - Lullabye.mp3
D:\eclipse\workspace\homework\src\房祖名 - 最好的我.mp3
----Find end----
学习心得
本来想把要查找的路径在代码中敲出,但是好像涉及到字符串中的反斜杠问题…不知道有没有什么好的处理方法?因此改用了自己输入路径的方式。