- package com.files;
- import java.io.*;
- import java.util.*;
- public class FilesTest2 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- File a=new File("G:\\JAVAWORK\\Io");
- List <File>list=new ArrayList<File>();
- FileToList(a,list);
- System.out.println(list.size());
- try {
- FileToWriter(list,"c:/a.txt");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static void FileToList(File dir,List<File> list){//递归查找文件夹的文件
- File [] file=dir.listFiles();
- for(File a:file){
- if(a.isDirectory())
- FileToList(dir,list);
- else
- {
- if(a.getName().endsWith(".java"))
- list.add(a);
- }
- }
- }
- public static void FileToWriter(List<File> list,String file)throws Exception{//把是.java文件读入c:/a.txt
- BufferedWriter bw=new BufferedWriter(new FileWriter(file));
- for(File a:list){
- String path=a.getAbsolutePath();
- bw.write(path);
- bw.newLine();
- }
- bw.flush();
- bw.close();
- }
- }
复制代码 读一个文件下没有子文件夹没问题,读一文件下有子文件夹就会出现以下问题:
Exception in thread "main" java.lang.StackOverflowError
at java.io.Win32FileSystem.resolve(Win32FileSystem.java:237)
at java.io.File.<init>(File.java:207)
at java.io.File.listFiles(File.java:1056)
at com.files.FilesTest2.FileToList(FilesTest2.java:25)
at com.files.FilesTest2.FileToList(FilesTest2.java:28)
at com.files.FilesTest2.FileToList(FilesTest2.java:28)
at com.files.FilesTest2.FileToList(FilesTest2.java:28)
at com.files.FilesTest2.FileToList(FilesTest2.java:28)
at com.files.FilesTest2.FileToList(FilesTest2.java:28)
at com.files.FilesTest2.FileToList(FilesTest2.java:28)
|