【问题标题】:Not able to delete image from external storage programmatically in android studio无法在 android studio 中以编程方式从外部存储中删除图像
【发布时间】:2020-01-11 09:45:24
【问题描述】:

我是 Android Studio 的初学者,我只想帮助从文件夹中删除图像,这是我的 代码我已经添加了图像并添加了一个按钮以将其保存在外部文件夹中,只是想删除它

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button)findViewById(R.id.button1);
    imageview = (ImageView)findViewById(R.id.imageView1);
    bytearrayoutputstream = new ByteArrayOutputStream();

    button.setOnClickListener(new View.OnClickListener() {


        public void onClick(View v) {
            // TODO Auto-generated method stub


            Drawable drawable = getResources().getDrawable(R.drawable.barcode);

            Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

            bitmap.compress(Bitmap.CompressFormat.PNG, 60, bytearrayoutputstream);

            file = new File( Environment.getExternalStorageDirectory() + "/SampleImage.png");

            try

            {
                file.createNewFile();

                fileoutputstream = new FileOutputStream(file);

                fileoutputstream.write(bytearrayoutputstream.toByteArray());

                fileoutputstream.close();

            }

            catch (Exception e)

            {

                e.printStackTrace();

            }


            Toast.makeText(MainActivity.this, "Image Saved Successfully", Toast.LENGTH_LONG).show();

        }
    });
}

} 如果您支持我获取知识,那将非常有帮助

【问题讨论】:

  • File.delete() ?
  • Toast.makeText(MainActivity.this, "Image Saved Successfully", Toast.LENGTH_LONG).show(); 不。你不能在这里说,因为也许有一个例外。将 toast 放入 try 块中,将不同的 Toast 放入 catch 块中,以在失败时通知用户和您自己。
  • file.createNewFile(); 删除该行。该文件将由新的 FileOutputStream() 创建。
  • 当问题与 Android Studio 无关时,不明白为什么人们一直在他们的问题标题后面附加“in Android Studio”......

标签: java android file


【解决方案1】:
final String where = MediaStore.MediaColumns.DATA + "=?";
final String[] selectionArgs = new String[]{
        f.getAbsolutePath()
};
final ContentResolver contentResolver = getContentResolver();
final Uri filesUri = MediaStore.Files.getContentUri("external");
contentResolver.delete(filesUri, where, selectionArgs);
// if (f.exists()) {
//     contentResolver.delete(filesUri, where, selectionArgs);
//     f.delete();
// }

【讨论】:

  • 我们已经在 try 块中写了这个??
  • 不需要。如果你想你可以放,因为有些时候文件不存在应用程序崩溃所以在这个方法之前你必须检查文件是否存在。
  • 您的回答只会让 OP 感到困惑,因为它与以正常方式删除文件无关。
猜你喜欢
  • 2017-12-28
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 2015-04-07
  • 2020-07-01
相关资源
最近更新 更多