Java修改文件夹下所有文件名

惯例:

我是温浩然:

最近,由于某些特殊情况,需要在一个文件夹下,修改所有文件的名字,

所有文件名加前缀。

代码如下:

import java.io.File;
public class Demo{
    public static void main(String[] args) {
        String path = "D://faceImages";  
        
        File file = new File(path);
        File[] array = file.listFiles(); 
        
        for(int i=0;i<array.length;i++){   
            if(array[i].isFile()){   
                File person = array[i];
                String _fileName = person.getName();
                StringBuffer ic = new StringBuffer();
                ic.append("ic_");
                ic.append(_fileName);
                String newName = ic.toString();
                System.out.println("名字是:"+newName);
                if (person.renameTo(new File(newName))){
                 System.out.println("修改成功!");
                }else{
                 System.out.println("修改失败");
                }
            }else if(array[i].isDirectory()){   
                //getFile(array[i].getPath());
                System.out.println("错误了");
            }   
        }   
    }

}

挺简单的。但是有这么一个情况需要注意。

(person.renameTo(new File(newName)))

这个地方,名字写的只是文件名,默认的路径,就是当前文件所在的目录。。

所以,被修改的文件,在原来的目录就会消失,出现在当前所在的目录。

别的没啥太难的。

评论

暂无评论