删除功能不起作用

时间:2013-09-18 08:13:56

标签: android file download delete-file

我正在开发一个应用程序,它有一个下载几个文件的启动画面,在文件开始下载之前我想检查文件是否已经存在,如果它们存在,我想删除它们。下面显示的代码包含正确的文件路径和检查文件是否存在的函数似乎在Logcat状态下读取“文件已删除”。

然而,当我检查手机本身时,我看到每当我启动应用程序时,会有更多文件被添加到具有相同文件名但数量不断增加的文件夹中

e.g。发射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();方法(下载文件的方法)时,它确实删除了文件,所以我认为文件开始下载之前删除的文件真的卡在这个上了?!

5 个答案:

答案 0 :(得分:3)

试试这个

void deleteExternalStoragePublicPicture() {
   // Create a path where we will place our picture in the user's
   // public download directory and delete the file.  If external
   // storage is not currently mounted this will fail.
      File path = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_DOWNLOADS);
      File file = new File(path, "DemoPicture.jpg");
      file.delete();
}

答案 1 :(得分:0)

File file = new File(selectedFilePath);
boolean deleted = file.delete();

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

/sdcard/YourCustomDirectory/ExampleFile.mp3

如果不起作用,请检查路径

答案 2 :(得分:0)

这可能是因为您没有

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

或者因为您在下载后尚未发布该文件的句柄。 如果您在该文件上打开了任何文件通道或输入Streams或缓冲读取器,则应在尝试删除该文件之前将其关闭。

答案 3 :(得分:0)

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"/>

答案 4 :(得分:0)

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

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