如果文件存在于目录中,如何覆盖该文件

时间:2016-08-29 05:03:54

标签: java android

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

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

并且这个时间文件不在这里因为吐司没有出现。

3 个答案:

答案 0 :(得分:2)

将此行添加到您的代码

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

答案 1 :(得分:1)

首先,让我们在AndroidManifest.xml文件中插入权限(少于Android 6.0版本)

android:name="android.permission.WRITE_INTERNAL_STORAGE" />

然后,使用以下代码将位图写入文件

String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "FitnessGirl"+".jpg"); // the File to save to
fOut = new FileOutputStream(file);
Bitmap pictureBitmap = content.getDrawingCache();// Your bitmap
//Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush();
fOut.close(); // do not forget to close the stream

MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

答案 2 :(得分:0)

试试这个,

boolean result = Files.deleteIfExists(file.toPath()); 

还要确保您已启用写入权限!

PS:在Android Lollipop中,您需要runtime permission,并且已在清单文件中设置的权限将无效。