Android file 文件重命名删除详解

开发中会有些需求对文件重命名,删除等操作,就需要调用File的方法来操作
1,重命名具体如下:

 /** *//**文件重命名
     * @param path 文件目录
     * @param oldname  原来的文件名
     * @param newname 新文件名
     */
    public boolean renameFile(String path,String oldname,String newname){
        boolean isResult = false;
        if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
            int index = path.lastIndexOf("/");
            File oldfile=new File(path.substring(0,index)+"/"+oldname);
            File newfile=new File(path.substring(0,index)+"/"+newname);
            if(!oldfile.exists()){
                return false;//重命名文件不存在
            }
            if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名
                Toast.makeText(mContext,mContext.getResources().getString(R.string.newfile_exits),Toast.LENGTH_SHORT).show();
            else{
               isResult = oldfile.renameTo(newfile);
            }
        }
        return isResult;
    }

2.删除文件

File file = new File(str);
 file.delete();
发布了262 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/baidu_41666295/article/details/105593319
今日推荐