从android中的文件夹中仅删除.jpg文件

时间:2013-05-16 13:25:44

标签: android

这是从文件夹中仅删除.jpg文件的任何方法吗? 这是我的删除方法:

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

如何从文件夹中仅删除.jpg文件?

3 个答案:

答案 0 :(得分:7)

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

或者您更喜欢for-each版本

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

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

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

然后致电

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