1

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

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

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

4

3 回答 3

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();
            }
}
于 2013-05-16T13:27:18.760 回答
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();
            }
        }
    }
于 2013-05-16T13:28:50.683 回答
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();    
}
}
}  
}    
}
于 2013-05-16T13:30:22.780 回答