删除多个文件Java(Android)

时间:2013-06-11 15:32:01

标签: java android file

我是Android的编程新手,我想删除SD卡上的文件。这是我目前的(工作)代码......

File appvc = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath(), "ApplifierVideoCache");

if (appvc.isDirectory()) {
            String[] children = appvc.list();
            for (int i = 0; i < children.length; i++) {
                new File(appvc, children[i]).delete();
            }
}

现在我想删除多个文件,但不想提及那个大块的每个文件。我能将所有文件合并到一个变量中吗?谢谢;)

5 个答案:

答案 0 :(得分:3)

制作递归方法:

/*
 * NOTE: coded so as to work around File's misbehaviour with regards to .delete(),
 * which does not throw an exception if it fails -- or why you should use Java 7's Files
 */

public void doDelete(final File base)
    throws IOException
{
    if (base.isDirectory()) {
        for (final File entry: base.listFiles())
            doDelete(entry);
        return;
    }

    if (!file.delete())
        throw new IOException ("Failed to delete " + file + '!');
}

答案 1 :(得分:1)

另一种可能性是使用Apache commons-io库并调用

if (file.isDirectory())
    FileUtils.deleteDirectory(File directory);
else {
    if(!file.delete())
        throw new IOException("Failed to delete " + file);
}

答案 2 :(得分:0)

你应该从这段代码中创建一个方法,传递文件名并随时调用它:

public void DeleteFile(String fileName) {
File appvc = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath(), fileName);

if (appvc.isDirectory()) {
            String[] children = appvc.list();
            for (int i = 0; i < children.length; i++) {
                new File(appvc, children[i]).delete();
            }
}
}

答案 3 :(得分:0)

File dir = new File(android.os.Environment.getExternalStorageDirectory(),"ApplifierVideoCache");

然后致电

deletedir(dir);

public void deletedir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
   listFile[i].delete();    
}  
}    
}

或者如果你的文件夹是子文件夹那么

public void walkdir(File dir) {

File listFile[] = dir.listFiles();

if (listFile != null) {
for (int i = 0; i < listFile.length; i++) 
{
    if (listFile[i].isDirectory()) 
    {
       walkdir(listFile[i]);
    } else 
      {
       listFile[i].delete();    
      }
}
}  

答案 4 :(得分:0)

对于Kotlin

创建路径列表数组

    val paths: MutableList<String> = ArrayList()
    paths.add("Yor path")
    paths.add("Yor path")
    .
    .

删除每个路径的文件

   try{
        paths.forEach{
             val file = File(it)
             if(file.exists(){
                  file.delete()
                }
         }
   }catch(e:IOException){

   }