java实现输出文件夹下某个格式的所有文件实例代码

时间:2022-11-21 22:16:52

java实现输出文件夹下某个格式的所有文件实例代码

java" id="highlighter_283369">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package file;
import java.io.file;
/**
 * 输出某个文件夹下所有某个格式的文件
 * @author hasee
 *
 */
public class demo2 {
 public static void main(string[] args) {
  gettxtname("d:/a",".jpg");
 }
 public static void gettxtname(string path,string suffix) {
  //判断文件对象是文件还是文件夹
  //构建文件对象
  file f = new file(path);
  //根据文件或者文件夹处理
  if(f.isfile()) {
   if(f.getname().endswith(suffix)) {
    system.out.println(f.getabsolutepath());
   }
  }else {
   //遍历文件夹
   file[] files = f.listfiles();
   if(files!=null && files.length>0) {
    //继续递归得到的文件或文件夹
    for (file file : files) {
     gettxtname(file.getabsolutepath(),suffix);
    }
   
  }
 }
}

2.删除文件夹下某个格式的所有文件

java实现输出文件夹下某个格式的所有文件实例代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package file;
import java.io.file;
public class demo3 {
 public static void main(string[] args) {
  // todo auto-generated method stub
  delete("d:/a",".jpg");
 }
 public static void delete(string path,string suffix) {
  file f = new file(path);
  if(f.isfile()) {
   if(f.getname().endswith(suffix)) {
    system.out.println(f.getabsolutepath()+"成功删除");
    f.delete();
   }
  }else {
   file[] files = f.listfiles();
   if(files!=null&&files.length>0) {
    for (file file : files) {
     delete(file.getabsolutepath(),suffix);
    }
   }
  }
 }
}

总结

以上所述是小编给大家介绍的java实现输出文件夹下某个格式的所有文件实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://blog.csdn.net/qq_32539825/article/details/80693901