Delete only .jpg files from folder in android

匿名 (未验证) 提交于 2019-12-03 09:52:54

问题:

This is any way to delete only .jpg files from folder? This is my remove method:

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

How can I remove only .jpg files from folder?

回答1:

if (dir.isDirectory()) {         String[] children = dir.list();         for (int i = 0; i < children.length; i++) {             String filename = children[i];             if (filename.endsWith(".jpeg") || filename.endsWith(".jpg"))                 new File(dir, filename).delete();         }  } 

or you prefer the for-each version

 if (dir.isDirectory()) {             String[] children = dir.list();             for (String child : children) {                 if (child.endsWith(".jpeg") || child.endsWith(".jpeg"))                     new File(dir, child).delete();             } } 


回答2:

Try like this

if (dir.isDirectory()) {         String[] children = dir.list();         for (int i = 0; i < children.length; i++) {             if(children[i].endsWith('.jpg' || children[i].endsWith('.jpeg'))             {                 new File(dir, children[i]).delete();             }         }     } 


回答3:

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

Then call

walkdir(dir);  public void walkdir(File dir) { String Patternjpg = ".jpg";  File listFile[] = dir.listFiles();  if (listFile != null) { for (int i = 0; i < listFile.length; i++) {  if (listFile[i].isDirectory()) { walkdir(listFile[i]); } else { if (listFile[i].getName().endsWith(Patternjpg)){   //Do what ever u want    listFile[i].delete();     } } }   }     } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!