java核心编程之文件过滤类FileFilter和FilenameFilter

网友投稿 265 2023-04-16


java核心编程之文件过滤类FileFilter和FilenameFilter

本文实例为大家分享了文件过滤类FileFilter和FilenameFilter,供大家参考,具体内容如下

1.FileFilter

package test;

import java.io.File;

import java.io.FileFilter;

public class FileFilterTest implements FileFijRIdPYkXlter {

private String extension;

public FileFilterTest(String extension) {

this.extension = extension;

}

/**

*

*/

@Override

public boolean accept(File pathname) {

if(pathname.isDirectory()){

return false;

}

String name = pathname.getName();

int num = name.lastIndexOf(".");

if(num == -1){

return false;

}

if(name.length()-1 == num){

return false;

} else {

return extension.equals(name.substring(num+1));

}

}

public static void main(String[] args) {

File path = new File("E:\\书籍\\java 编程");

//获得过滤对象

FileFilterTest ft = new FileFilterTest("pdf");

File[] files = path.listFiles(ft);

for (int i = 0; ijRIdPYkX < files.length; i++) {

System.out.println(files[i].getAbsolutePath());

}

}

}

2.FilenameFilter

package test;

import java.io.File;

import java.io.FilenameFilter;

public class jRIdPYkXFileNameFilterTest implements FilenameFilter {

//判断图片是否格式是否是 gif

private boolean isGif(String fileName){

if(fileName.toLowerCase().endsWith(".gif")){

return true;

} else {

return false;

}

}

//判断图片是否格式是否是 jpg

private boolean isJpg(String fileName){

if(fileName.toLowerCase().endsWith(".jpg")){

return true;

} else {

return false;

}

}

//判断图片是否格式是否是 png

private boolean isPng(String fileName){

if(fileName.toLowerCase().endsWith(".png")){

return true;

} else {

return false;

}

}

@Override

public boolean accept(File dir, String name) {

return (isGif(name)||isJpg(name)||isPng(name));

}

public static void main(String[] args) {

File path = new File("C:\\img");

//获得过滤对象

FileNameFilterTest ft = new FileNameFilterTest();

File[] f = path.listFiles(ft);

for (int i = 0; i < f.length; i++) {

File file = f[i];

System.out.println(file.getAbsolutePath());

}

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:bootstrap fileinput实现文件上传功能
下一篇:浅谈SpringMVC之视图解析器(ViewResolver)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~