【问题标题】:myFile.delete(); does not delete file properly android我的文件.delete();没有正确删除文件android
【发布时间】:2014-03-04 05:13:15
【问题描述】:

我有一段代码,它基本上裁剪用户选择的图像,并应该用新图像覆盖图像“CurrentProfilePic.jpg”。它首先删除图像(如果存在)然后创建它再次。但图像没有被删除。所以没有。代码运行的次数,没有。的图像是用相同的名称创建的。我使用日志来查看 file.delete();返回真,它确实返回真。

public void cropImage(View v) {
    bitmap=cropImageView.getCroppedImage();
boolean imageSaved = false;
String imageName="CurrentProfilePic";
//to save current image to directory
    if (bitmap != null && !bitmap.isRecycled()) {
        File storagePath = new File(
                Environment.getExternalStorageDirectory() + "/SimpleMessaging/");

        if (!storagePath.exists()) {
            storagePath.mkdirs();
        }
        File temp= new File(Environment.getExternalStorageDirectory() + "/SimpleMessaging/CurrentProfilePic.jpg");
        if(temp.exists()){
            boolean x= temp.delete();
            Log.d("PICS", "Inside if exist of pic");
            if(x)
                Log.d("bool", "x true");
            else
                Log.d("bool", "x false");
        }
        FileOutputStream out = null;
        File imageFile = new File(storagePath, String.format("%s.jpg",
                imageName));


        try {
            out = new FileOutputStream(imageFile);
            imageSaved = bitmap.compress(Bitmap.CompressFormat.JPEG,
                    100, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            Log.e("SaveToSD ", "Unable to write the image to gallery" + e);

        }

        ContentValues values = new ContentValues(3);
        values.put(Images.Media.TITLE, imageName);
        values.put(Images.Media.MIME_TYPE, "image/jpeg");
        values.put("_data", imageFile.getAbsolutePath());

        getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);

    }
    startActivity(new Intent(getBaseContext(), EditProfilePic.class));
    finish();
}

需要强调的是,这些文件中的每一个都会覆盖最新的图像,但它们的大小并没有改变,它们的原始大小。

【问题讨论】:

  • “创建了许多具有相同名称的图像”——根据定义,一个目录中不能有两个或多个同名文件。
  • @CommonsWare 我很清楚这一点,但看到这一点我很震惊。这是我从目录中截取的屏幕截图的链接:postimg.org/image/4quomv603
  • 当您通过 DDMS 或 adb shell 检查设备本身时,您看到了什么?
  • 我使用了终端模拟器并在目录上使用了 ls 命令。它只显示了 1 个文件!那么windows explorer怎么可能显示多个呢??

标签: android image file


【解决方案1】:

删除getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);及其支持代码。 Use MediaScannerConnectionACTION_MEDIA_SCANNER_SCAN_FILE 为您的文件编制索引。

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 2015-05-28
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多