1

我是 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();
            }
}

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

4

5 回答 5

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 + '!');
}
于 2013-06-11T15:36:55.730 回答
1

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

if (file.isDirectory())
    FileUtils.deleteDirectory(File directory);
else {
    if(!file.delete())
        throw new IOException("Failed to delete " + file);
}
于 2015-02-02T15:42:40.090 回答
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();
            }
}
}
于 2013-06-11T15:34:35.197 回答
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();    
      }
}
}  
于 2013-06-11T15:36:19.953 回答
0

对于科特林

创建一个路径列表数组

    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){

   }
于 2020-09-26T01:56:03.887 回答