扫描某路径下的文件
示例
通过扫描某路径下的文件夹和文件,
用字符串处理得到的全限定名,
然后使用List<String>输出里边的文件
public class ScanFiles {
public static void scanFiles(String path, List<String> fileList) {
File file = new File(path);
if (!file.exists()) {
System.out.println("指定路径不存在!");
return;
}
if (file.isFile()) {
fileList.add(file.getAbsolutePath());
return;
}
File[] files = file.listFiles();
for (File subFile : files) {
if (subFile.isDirectory()) {
scanFiles(subFile.getAbsolutePath(), fileList);
} else {
fileList.add(subFile.getAbsolutePath());
}
}
}
public static void main(String[] args) {
String path = "D:\\QQMusic";
List<String> fileList = new ArrayList<>();
scanFiles(path, fileList);
for (String fileName : fileList) {
// 进行字符串处理,得到全限定名
String fullName = fileName.replace("\\", ".");//把"\\"替换成".",然后输出打印
fullName = fullName.substring(fullName.indexOf("指定路径") + 4, fullName.lastIndexOf("."));
System.out.println(fullName);
}
}
}
运行结果: