如何从存储中删除文件

时间:2016-02-08 12:08:16

标签: android delete-file

我有一个内容菜单,当你在几秒钟内按下该项目时会弹出一个重命名和删除菜单。但我不知道如何获得一个文件的正确目录。这是我的代码:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId()) {
        case R.id.rename:
            // edit stuff here
            return true;
        case R.id.delete:

            File dir = new File(Environment.getExternalStorageDirectory()+"/Music/MusicPlayer");
            if (dir.isDirectory())
            {
                String[] children = dir.list();
                for (int i = 0; i < children.length; i++)
                {
                    new File(dir, children[i]).delete();
                }
            }

            // remove stuff here
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

4 个答案:

答案 0 :(得分:6)

使用以下util函数删除文件或目录。

public static boolean delete(File path) {
    boolean result = true;
    if (path.exists()) {
        if (path.isDirectory()) {
            for (File child : path.listFiles()) {
                result &= delete(child);
            }
            result &= path.delete(); // Delete empty directory.
        } else if (path.isFile()) {
            result &= path.delete();
        }
        return result;
    } else {
        return false;
    }
}

用法:

File dir = new File(Environment.getExternalStorageDirectory()+"/Music/MusicPlayer");
delete(dir);          

答案 1 :(得分:0)

而不是使用String [] children = dir.list()尝试使用:

File dir = new File(PATH);
File[] children = dir.listFiles();
for(int i = 0; i < children.length; i++) {
   children[i].delete();
}

答案 2 :(得分:0)

使用以下功能从文件夹中删除文件,只需在参数中传递文件夹路径,如

File fDir = new File(PERENT_PATH);
DeleteRecursive(fDir);
// where PERENT_PATH = Environment.getExternalStorageDirectory()+"/folderName"
public static void DeleteRecursive(File fileOrDirectory) {
        if (fileOrDirectory.isDirectory())
            for (File child : fileOrDirectory.listFiles())
                DeleteRecursive(child);

        if (fileOrDirectory.exists()) {
            boolean b = fileOrDirectory.delete();
            if (b) {
                Log.e( "delete dir", "delete dir");
            } else {
                Log.e( "not delete dir", "not delete dir");
            }
        }
    }

答案 3 :(得分:0)

请查看以下代码

select * from 
(select top 1 * from Table
where type = 'New'
order by priority asc) New
union
select * from 
(select top 1 * from Table
where type = 'Old'
order by priority asc) Old