如何从外部存储器中删除文件的代码

时间:2015-07-16 06:42:45

标签: java android file

我使用此代码从外部存储器删除文件。但它无法删除(“未删除”)。我该怎么办?

主要课程

public void deleteButtonClicked(View v) {
    deleteExternalStoragePrivateFile();
}

private void deleteExternalStoragePrivateFile() {
    File path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    if (path != null) {

        if(getApplicationContext().deleteFile("OneRepublic_-_Something_I_Need.mp3"))
        {
            Toast.makeText(getApplicationContext(),"File Deleted",Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(getApplicationContext(),"Not Deleted",Toast.LENGTH_SHORT).show();
        }
    }
}

}

4 个答案:

答案 0 :(得分:1)

Context.deleteFile("")删除与此Context的应用程序包关联的给定文件。

如果您想删除文件,可以使用此代码。以下是实际来源的link

public void deleteFile(String[] args)
    {   
        try{

            File file = new File("c:\\logfile20100131.log");

            if(file.delete()){
                System.out.println(file.getName() + " is deleted!");
            }else{
                System.out.println("Delete operation is failed.");
            }

        }catch(Exception e){

            e.printStackTrace();

        }

    }

答案 1 :(得分:0)

尝试使用此代码进行删除

getItem

答案 2 :(得分:0)

您是否提供了必要的权限?

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

如果您确实拥有权限,则可以按照其他答案中的建议使用file.delete()。

修改

private void deleteExternalStoragePrivateFile() {
File path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (path != null) {

    for(File f:path.listFiles()){
        String name = f.getName();
        if(name.contains("OneRepublic_-_Something_I_Need.mp3")){
            if(f.delete())
            {
                Toast.makeText(getApplicationContext(),"File Deleted",Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(),"Not Deleted",Toast.LENGTH_SHORT).show();
            }
        }
    }
}

}

答案 3 :(得分:0)

//Find base directory - file
File file = getApplicationContext()
        .getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (!file.exists()) {
    file.mkdirs();
}

//Find your file path
File filePath = new File(file, YOUR_FILE_NAME);

//Delete your file
if(! filePath.exists())
    return;
else
    filePath.delete();

确保您在清单中添加了以下权限

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