您的位置:首页 > 其它

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

2015-08-27 12:43 253 查看
不多说,直接贴例子

/**

     * 重命名文件名,新文件名不加后缀

     * @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最终要是一个路径,而不是一个文件名,之前因为只写文件名,所以一直不成功。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: