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);

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...