【问题标题】:Delete a File from the apps private storage directory - Android从应用程序私有存储目录​​中删除文件 - Android
【发布时间】:2014-02-20 18:43:07
【问题描述】:

我在尝试从我以编程方式创建和压缩的应用程序私有存储目录​​中删除文件时遇到了一些麻烦。

我面临的问题是当我调用 file.exists() 时它没有识别出文件存在,所以它不会删除文件。

这是我用来删除文件的代码

public static void deleteImageFromPrivateArea( final String fileUri )
  {
    final File file;
    boolean isFileDeleted;
    if ( isFilePathPrefixPresent( fileUri ) )
    {//file name checking
      file = new File( fileUri );
    }
    else
    {
      file = new File( "file://" + fileUri );
    }

    if ( file.exists() )
    {
      isFileDeleted = file.delete();
      if ( ! isFileDeleted )
      {
        throw new IllegalStateException( "File was not deleted" );
      }
    }
  }
  1. 为了清楚起见,我知道我正在传递的 fileUri 是当前存在的文件的位置。我已经使用文件管理器应用进行了检查。

  2. 我在清单 xml 中设置了权限。

  3. 我认为正在发生的事情是这段代码正在获取当前存在文件的路径,并设置了一个新文件但没有将数据写入其中,因此这个新文件在 android 中不存在。

所以我认为我需要做的是获取现有文件(可能不是以 Uri 的形式,而是实际文件),然后调用 .delete() ,因为这样文件就会存在。

或者

在使用 fileUri 设置这个新文件后,使用 OutputfileStream 将数据写入其中 - 虽然这不是我的首选方法。

-但我不完全确定。

【问题讨论】:

    标签: file-io android-file android


    【解决方案1】:

    将文件名作为参数传递会更容易

     File mydir = getFilesDir(); //get your internal directory
     File myFile = new File(mydir, filename);
     myFile.delete();
    

    【讨论】:

    • 您好,感谢您的帮助!这让我接近了我需要的东西。而不是使用 getFilesDir() 我使用 getExternalFilesDir( Environment.DIRECTORY_PICTURES )
    【解决方案2】:

    在 BradR 的帮助下,我找到了最佳解决方案。

    1. 我使用*getExternalFilesDir(Environment.DIRECTORY_PICTURES)*获取图片2.应用程序私有存储区的目录。

    2. 使用给定的 imageUri 创建了一个新文件,然后使用它来获取文件的文件名。

    3. 使用 ExternalFilesDirfilename

    4. 重新初始化文件以创建新文件
    5. 检查文件是否存在并删除。

    #

      public static void deleteImageFromPrivateArea( final Context context, final String imageUri )
      {
        String filename;
        File file;
        final File dir = context.getExternalFilesDir( Environment.DIRECTORY_PICTURES );
    
        if ( isFilePathPrefixPresent( imageUri ) )
        {
          file = new File( imageUri );
        }
        else
        {
          file = new File( "file://" + imageUri );
        }
    
        filename = file.getName();
        file = new File( dir, filename );
    
        if ( file.exists() )
        {
          try
          {
            file.delete();
          }
          catch ( Exception e )
          {
            throw new IllegalStateException( "File wasn't deleted" );
          }
        }
        else
        {
          throw new IllegalStateException( "File was doesn't exist" );
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 2019-10-20
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多