【问题标题】:Delete function not working删除功能不起作用
【发布时间】:2013-09-18 08:13:56
【问题描述】:

我正在开发一个应用程序,它有一个下载几个文件的启动屏幕,在文件开始下载之前我想检查文件是否已经存在,如果它们存在我想删除它们。下面显示的代码包含正确的文件路径,并且检查文件是否存在的功能似乎可以正常工作,因为 Logcat 中的读出状态为“文件已删除”。

但是,当我检查手机本身时,我发现每当我启动应用程序时,就会有 2 个文件被添加到文件夹中,文件名相同,但数字不断增加

例如启动 1... 我明白了

clientraw.txt
clientrawextra.txt

启动 2... 我明白了

clientraw.txt
clientrawextra.txt
clientraw-1.txt
clientrawextra-1.txt

等等……

因此,删除功能似乎不起作用,我们将不胜感激!

//Code that checks if the clientraw.txt file already exists, if so the file is deleted 
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() +
        "/Download", client);
Log.d("file path", String.valueOf(file));
if (file.exists()) {
    file.delete();
    Log.d("file", "file deleted");
}

File sdCardextra = Environment.getExternalStorageDirectory();
File fileextra = new File(sdCardextra.getAbsolutePath() +
        "/Download", clientextra);
if (fileextra.exists()) {
    fileextra.delete();
    Log.d("file", "file deleted");
}

ready();

似乎删除文件的速度不够快?当我摆脱ready();方法(下载文件的方法)时,它确实删除了文件,所以我认为文件在删除之前的文件之前就开始下载真的卡在这个了吗?!

【问题讨论】:

  • Log.d("文件", "文件已删除");在控制台中打印?
  • 在日志中打印 file.getAbsolutePath() 并确认文件路径。如果该路径中存在文件,则 file.delete() 必须删除该文件。此外,您可以检查 file.delete() 返回的布尔值。
  • 我遇到了同样奇怪的问题。 file.delete() 返回 true,但它仍然存在并且可读。

标签: android file download delete-file


【解决方案1】:
public static boolean deleteDirectory(File path) {
// TODO Auto-generated method stub
if( path.exists() ) {
    File[] files = path.listFiles();
    for(int i=0; i<files.length; i++) {
        if(files[i].isDirectory()) {
            deleteDirectory(files[i]);
        }
        else {
            files[i].delete();
        }
    }
}
return(path.delete());
 }

此代码将帮助您..并且在 Android Manifest 中您必须获得许可才能进行修改..

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

【讨论】:

    【解决方案2】:
    File file = new File(selectedFilePath);
    boolean deleted = file.delete();
    

    其中 selectedFilePath 是您要删除的文件的路径 - 例如:

    /sdcard/YourCustomDirectory/ExampleFile.mp3
    

    如果不行,检查路径

    【讨论】:

    • 这段代码运行良好,很奇怪。你的问题来自其他地方:/
    • 是的,我意识到这不是删除,而是下载。由于某种原因,它会不断下载每个文件两次?! stackoverflow.com/questions/18879674/…
    【解决方案3】:

    要么是因为你没有权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    或者因为您在下载后尚未释放对该文件的处理。 如果您在该文件上打开了任何文件通道或输入流或缓冲读取器,则应在尝试删除文件之前关闭它们。

    【讨论】:

      【解决方案4】:

      您可以通过文件路径删除特定文件... 试试这个

      public static void deletFile(String file) {
          File f = new File(file);
          if (f.delete()) {
              Log.d("00000", "delete");
          }
          else{
              Log.d("00000", "Not delete");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-07-17
        • 2018-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        相关资源
        最近更新 更多