关于文件过滤的接口FileFilter的用法,先看一个简单代码package input;
import java.io.*;public class InAndOut { private static FileFilter fileFilter = new FileFilter()
{
public boolean accept(File pathname) {
String tmp = pathname.getName().toLowerCase();
if(tmp.endsWith(".txt")||tmp.endsWith(".doc")){
return true;
}
return false;
}
}; public static void main(String[] args) {
// TODO Auto-generated method stub
File root=new File("F:\\计算机技术\\小技巧");
File[] files=root.listFiles(fileFilter);
for(int i=0;i<files.length;i++)
{
System.out.println(files[i]);
} }}这段代码是我根据我的情况改的,运行结果都没问题。但是我对这段代码有些不理解
private static FileFilter fileFilter = new FileFilter()
{
public boolean accept(File pathname) {
String tmp = pathname.getName().toLowerCase();
if(tmp.endsWith(".txt")||tmp.endsWith(".doc")){
return true;
}
return false;
}
};
由于是新手,看书上说,一般接口是由类实现,然后从类中实现其方法。但是这段代码第一行,定义了一个接口变量,新建一个接口对象。但接下来为什么就直接大括号,然后里边并把接口的方法,给实现了。这是什么机制?请大家帮忙解释一下。不胜感激!
import java.io.*;public class InAndOut { private static FileFilter fileFilter = new FileFilter()
{
public boolean accept(File pathname) {
String tmp = pathname.getName().toLowerCase();
if(tmp.endsWith(".txt")||tmp.endsWith(".doc")){
return true;
}
return false;
}
}; public static void main(String[] args) {
// TODO Auto-generated method stub
File root=new File("F:\\计算机技术\\小技巧");
File[] files=root.listFiles(fileFilter);
for(int i=0;i<files.length;i++)
{
System.out.println(files[i]);
} }}这段代码是我根据我的情况改的,运行结果都没问题。但是我对这段代码有些不理解
private static FileFilter fileFilter = new FileFilter()
{
public boolean accept(File pathname) {
String tmp = pathname.getName().toLowerCase();
if(tmp.endsWith(".txt")||tmp.endsWith(".doc")){
return true;
}
return false;
}
};
由于是新手,看书上说,一般接口是由类实现,然后从类中实现其方法。但是这段代码第一行,定义了一个接口变量,新建一个接口对象。但接下来为什么就直接大括号,然后里边并把接口的方法,给实现了。这是什么机制?请大家帮忙解释一下。不胜感激!
楼主【roniejrd】截止到2008-06-30 10:19:25的历史汇总数据(不包括此帖):
发帖数:5 发帖分:80
结贴数:4 结贴分:80
未结数:1 未结分:0
结贴率:80.00 % 结分率:100.00%
楼主加油
{
public boolean accept(File pathname) {
String tmp = pathname.getName().toLowerCase();
if(tmp.endsWith(".txt") ¦ ¦tmp.endsWith(".doc")){
return true;
}
return false;
}
}; 这是匿名内部类 意思是有个类,一个没有名字的类,继承了FileFilter,FileFilter是一个接口,所以这个没名字的类要去实现接口中的所有方法,FileFilter只有一个方法boolean accept(File pathname)
所以下面代码是这个没名字的类实现 FileFilter的代码:
public boolean accept(File pathname) {
String tmp = pathname.getName().toLowerCase();
if(tmp.endsWith(".txt") ¦ ¦tmp.endsWith(".doc")){
return true;
}
return false;
}