package yang.www;
import java.io.File;
import java.io.FilenameFilter;
public class FileFilterTest
{
File file = new File(direcotry);
if ( file.isDirectory() )
{
String[] fileList = file.list();
for (int i=0; i<fileList.length; i++)
{
File tempFile = new File(direcotry + fileList[i]);
if (tempFile.isDirectory())
{
System.out.println(direcotry + fileList[i] + "\t\t目录");
}
else if (tempFile.isFile())
{
System.out.println(direcotry + fileList[i] + "\t\t文件");
}
if ( tempFile.isDirectory() )
{
this.displayDirectory(direcotry + fileList[i] + "/");
}
}
}
{
File file = new File(path);
if ( file.isDirectory() )
{
File[] fileList = file.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name)
{
return name.endsWith(".java");
}
});
for (int i=0; i<fileList.length; i++)
{
System.out.println(fileList[i].getName());
File temp = new File(path + fileList[i].getName());
if ( temp.isDirectory() )
{
dispalyDisplayJava(path + fileList[i].getName() + "/");
}
}
}
}
public static void main(String[] args)
{
String path = "/home/ubuntu/Desktop/javas/";
new FileFilterTest().displayDirectory(path);
new FileFilterTest().dispalyDisplayJava(path);
}
}
import java.io.File;
import java.io.FilenameFilter;
public class FileFilterTest
{
//这个方法只是列出目录下所有的文件以及子目录
{
File file = new File(direcotry);
if ( file.isDirectory() )
{
String[] fileList = file.list();
for (int i=0; i<fileList.length; i++)
{
File tempFile = new File(direcotry + fileList[i]);
if (tempFile.isDirectory())
{
System.out.println(direcotry + fileList[i] + "\t\t目录");
}
else if (tempFile.isFile())
{
System.out.println(direcotry + fileList[i] + "\t\t文件");
}
if ( tempFile.isDirectory() )
{
this.displayDirectory(direcotry + fileList[i] + "/");
}
}
}
}
//只列出特定后缀的文件
{
File file = new File(path);
if ( file.isDirectory() )
{
File[] fileList = file.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name)
{
return name.endsWith(".java");
}
});
for (int i=0; i<fileList.length; i++)
{
System.out.println(fileList[i].getName());
File temp = new File(path + fileList[i].getName());
if ( temp.isDirectory() )
{
dispalyDisplayJava(path + fileList[i].getName() + "/");
}
}
}
}
public static void main(String[] args)
{
String path = "/home/ubuntu/Desktop/javas/";
new FileFilterTest().displayDirectory(path);
new FileFilterTest().dispalyDisplayJava(path);
}
}
本文介绍了一个Java程序,用于展示如何列出指定目录下的所有文件及子目录,并且能够筛选出特定类型的文件,如.java文件。通过使用File类和FilenameFilter接口,实现了递归遍历目录结构的功能。
221

被折叠的 条评论
为什么被折叠?



