1:列出指定文件夹下的文件名称
- package IO流练习;
- /**
- * 把指定的文件夹下的文件全部列出,并把名称和路径打印到list.txt文件中
- */
- import java.io.*;
- import java.util.*;
- public class 列出文件列表 {
- public static void main(String[] args)throws Exception {
- File dir = new File("D:\\heima");
- Collection<String> con = new ArrayList<String>();
-
- printListFileName(dir,con);
- }
- public static void printListFileName(File dir,Collection<String> con) throws Exception
- {
-
- //System.out.println(dir.getAbsolutePath());
- con.add(dir.getCanonicalPath());
- File [] files = dir.listFiles();
- for (File file : files) {
- if(file.isDirectory())
- {
- printListFileName(file,con);
- }else
- {
- String name = file.getAbsolutePath();
- //System.out.println(name);
- con.add(name);
- }
- }
- writeFile(con);
- }
- public static void writeFile(Collection<String> con) throws Exception
- {
- BufferedWriter bw = new BufferedWriter(
- new FileWriter("D:\\2014list.txt"));
- Iterator<String> it = con.iterator();
- while(it.hasNext())
- {
- bw.write(it.next());
- bw.flush();
- bw.newLine();
- }
- bw.close();
- }
- }
复制代码
2:列出指定文件夹下的文件名称并过滤指定的文件
- package IO流练习;
- import java.io.*;
- import java.util.*;
- public class 列出指定文件并过滤 {
- public static void main(String[] args) throws Exception{
- File dir = new File("D:\\heima");
- listFileName(dir);
- }
- public static void listFileName(File dir) throws Exception
- {
- BufferedWriter bw = new BufferedWriter(
- new FileWriter("D:\\2014list.txt"));
- File [] files = dir.listFiles();
- for (File file : files) {
- if(file.isDirectory())
- {
- String [] fileName = file.list(new FilenameFilter()
- {
- public boolean accept(File dir, String name) {
- // TODO Auto-generated method stub
- return name.endsWith(".java");
- }
- });
- for(int j = 0;j<fileName.length;j++)
- {
- bw.write(file.getAbsolutePath()+File.separator+fileName[j]);
-
- bw.newLine();
- }
- listFileName(file);
- }else
- {
- bw.write(file.getAbsolutePath());
-
- bw.newLine();
- }
- }
- bw.close();
-
-
-
- }
- }
复制代码
|