一下是代码:
import java.io.File;
public class test {
public static void main(String[] args) {
// 这是需要获取的文件夹路径
String path = "D:/changba20180127/music/";
getFile(path, 0);
}
/*
* 函数名:getFile 作用:使用递归,输出指定文件夹内的所有文件 参数:path:文件夹路径 deep:表示文件的层次深度,控制前置空格的个数
* 前置空格缩进,显示文件层次结构
*/
private static void getFile(String path, int deep) {
// 获得指定文件对象
File file = new File(path);
// 获得该文件夹内的所有文件
File[] array = file.listFiles();
for (int i = 0; i < array.length; i++) {
if (array[i].isFile())// 如果是文件
{
// for (int j = 0; j < deep; j++)//输出前置空格
// System.out.print(" ");
if (accept(array[i], array[i].getName())) {
String name = array[i].getName();
// 只输出文件名字 TODO
System.out.println(name + "----");
//修改后的名字
// int indexOf = name.indexOf(" (1).mp3");
// String remeName = name.substring(0,indexOf)+".mp3";
// System.out.println(remeName);
// array[i].renameTo(new File("D:/changba20180127/original/"
// + remeName ));
} else {
System.out.println("==============");
}
// 输出当前文件的完整路径
// System.out.println("#####" + array[i]);
// 同样输出当前文件的完整路径 大家可以去掉注释 测试一下
// System.out.println(array[i].getPath());
} else if (array[i].isDirectory())// 如果是文件夹
{
for (int j = 0; j < deep; j++)
// 输出前置空格
System.out.print(" ");
System.out.println(array[i].getName());
// System.out.println(array[i].getPath());
// 文件夹需要调用递归 ,深度+1
getFile(array[i].getPath(), deep + 1);
}
}
}
// 重写accept方法,测试指定文件是否应该包含在某一文件列表中
public static boolean accept(File dir, String name) {
// TODO Auto-generated method stub
// 创建返回值
boolean flag = true;
// 定义筛选条件
// endWith(String str);判断是否是以指定格式结尾的
if (name.toLowerCase().endsWith(".jpg")) {
} else if (name.toLowerCase().endsWith(".txt")) {
} else if (name.toLowerCase().endsWith("(1).mp3")) {
flag = true;
} else {
flag = false;
}
// 返回定义的返回值
// 当返回true时,表示传入的文件满足条件
return flag;
}
}
设置搜索规则的函数是 accept() 中的判断条件。
这里稍微提一下一下两个函数:
startsWith方法测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
endsWith方法测试此字符串从指定索引开始的子字符串是否以指定尾缀结束。