写了个代码;
思路:
1:装载所有文件夹下的文件至集合(递归)
2:遍历内存集合中的文件,修改文件名
贴代码;- import java.io.File;
- import java.util.ArrayList;
- import java.util.List;
- public class FileRename {
- static final public String txt = "txt";
- static final public String path = "F:\\TextView";
-
- public static void main(String[] args) {
-
- List<File> files = getFiles(null , path);
- System.out.println("该文件夹拥有文件数:"+files.size());
-
- //更改文件名业务逻辑方法
- for(File f : files){
- System.out.println("=================================");
- System.out.println("更改前:"+f.getAbsolutePath());
- System.out.println("更改后:"+reNameFiles(f , txt));
- }
- System.out.println("=================================");
- System.out.println("恭喜您,您已经完全更改路径。");
-
- }
-
- /** 更改单个文件 */
- public static String reNameFiles(File f , String txt) {
- String name = f.getAbsolutePath();
- int index = name.lastIndexOf(".");
- File newF = null;
- if(index != -1){
- name = name.substring(0, index+1);
- newF= new File(name+txt);
- f.renameTo(newF);
- }
- else{
- newF = new File(f.getAbsoluteFile() ,"."+txt);
- f.renameTo(newF);
- }
- return newF.getAbsolutePath();
- }
- /**
- * 获取文件夹下所有文件
- * @return
- */
- public static List<File> getFiles(List<File> list , String dirPath){
- if(list == null) list = new ArrayList<File>();
- File dir = new File(dirPath);
- if(dir.isDirectory()){
- File[] childrenFiles = dir.listFiles();
- for(File childrenFile : childrenFiles){
- getFiles(list, childrenFile.getAbsolutePath());
- }
- }
- else{
- list.add(dir);
- }
- return list;
-
- }
-
-
- }
复制代码 |