文件和文件目录重命名问题

来源:互联网 发布:企业画像 大数据 编辑:程序博客网 时间:2024/05/19 00:54

不多说,直接贴例子

/**

     * 重命名文件名,新文件名不加后缀
     * @param filePath
     * @param newName
     */
    public static void rename(String filePath,String newName){
        File file=new File(filePath);
        
        if(!file.isDirectory()&&filePath.indexOf(".")!=-1){
            String suffix=filePath.substring(filePath.lastIndexOf(".")+1,filePath.length());
            newName=filePath.substring(0, filePath.lastIndexOf("/"))+newName+suffix;
        }else{
            //对目录进行处理
            String str;
            if(filePath.lastIndexOf("/")==filePath.length()-1){
                str=filePath.substring(0, filePath.length()-1);
            }else{
                str=filePath;
            }
            
            //截取当前文件目录名
            int index=str.lastIndexOf("/");
            String fileName=str.substring(index+1,str.length());
            
            //替换项目名为commonWeb的名字
            newName=filePath.replace(fileName,newName);
        }
        
        file.renameTo(new File(newName));

    }

这里的newName最终要是一个路径,而不是一个文件名,之前因为只写文件名,所以一直不成功。

0 0
原创粉丝点击