zhuxiaoleiking 发表于 2013-2-5 10:12:00

使用 file类 查询当前目录下的文件

01.//列出当前指定目录下的所有文件。   
02.package org.io.fieldemo;   
03.import java.io.*;   
04.
05.class FindFile {   
06.    private File f;   
07.    private String flname="";    //用于返回所要输出的文件名   
08.    private int count=0;         //对所查询到的文件个数进行计数   
09.      
10.    public File getF() {   
11.      return f;   
12.    }   
13.
14.    public void setF(File f) {   
15.      this.f = f;   
16.    }   
17.      
18.    public String getFlname() {   
19.      return flname;   
20.    }   
21.
22.    public void setFlname(String flname) {   
23.      this.flname = flname;   
24.    }   
25.
26.      
27.    public void getFileName(File f){      
28.      if(f.isFile()){               
29.            System.out.println(f.getName());    //如果当前对象是一个文件,则直接输出   
30.      }else{   
31.            File fl[] = f.listFiles();          //如果当前当想是一个目录,则通过listFiles()方法返回一个当前文件夹下的对象数组   
32.            for (int i=0;i<fl.length;i++){   
33.                if(fl.isFile()){   
34.                  flname = fl.getPath()+fl.getName()+"\n"+flname;   //输出返回的对象数组中文件的名称。   
35.                  count++;   
36.                }else{   
37.                  this.getFileName(fl);      //通过递归,把返回的对象数组中属于目录的对象传递给this.getFileName(File f);   
38.                }   
39.            }   
40.      }   
41.      
42.    }   
43.
44.    public int getCount() {   
45.      return count;   
46.    }   
47.
48.    public void setCount(int count) {   
49.      this.count = count;   
50.    }   
51.
52.
53.}   
54.
55.public class FileDemo04 {   
56.    public static void main(String[] args) throws Error {   
57.      File f = new File("f:\\FTP");   
58.      System.out.println("isDirectory:"+f.isDirectory());   
59.      FindFile ff = new FindFile();   
60.      ff.getFileName(f);   
61.      System.out.println("共查询到"+ff.getCount()+"个文件");   
62.      System.out.println(ff.getFlname());   
63.      }      
64.    }


本文是我抄自CSDN博客http://blog.csdn.net/xiaoxiinlose/archive/2009/12/31/5110036.aspx
页: [1]
查看完整版本: 使用 file类 查询当前目录下的文件