微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 如果文件存在于目录中,我该如何覆盖它

我将图像保存在我的目录中,具有相同的名称(出于某种目的)但是当文件已存在时,它不会被覆盖,我怎么知道?因为当我保存这个文件时,现有的文件没有改变,但是当我为我的文件使用不同的名称时,它可以工作.所以我想要的是用新的文件替换现有的文件.到目前为止,这正是我正在尝试的:

 content.setDrawingCacheEnabled(true);
                Bitmap bitmap = content.getDrawingCache(); // an bitmap file for saving


                File file = new File(context.getApplicationContext().getFilesDir() + "/img.jpg"); //here's the path where i'm saving my file

                if (file.exists()){

                    file.delete(); // here i'm checking if file exists and if yes then i'm deleting it but its not working 
                }


                String path = file.getPath();

                try {
                    file.createNewFile();
                    FileOutputStream ostream = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG,60,ostream);


                    savedFile = new File(path);


                    ostream.close();
                }
                catch (Exception e)
                {
                    e.printstacktrace();

                }

我在删除现有文件后立即进行另一次检查:

                if (file.exists()){

                    Toast.makeText(context,"Still EXISTS",Toast.LENGTH_SHORT).show();
                }

而这个时间文件在这里因为吐司没有出现.

最佳答案
将此行添加到您的代码

FileWriter fw = new FileWriter(myDir + "/score.jpg",false);

原文地址:https://www.jb51.cc/android/430044.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐