列出目录中的文件时出错

时间:2011-09-13 14:56:07

标签: java file

我有一个java类,用于列出给定目录的文件。它只适用于只有文件且没有子目录的目录。但是如果里面有一个子目录,它会给出java.lang.StackOverflowError异常。这是与main()方法一起使用的类:

package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DisplayFilesAndFolders {

    public static void main(String[] args) {
        try {
            List<File> files = getFileList();
            for(File file : files ){
              System.out.println(file);
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static List<File> getFileList() throws FileNotFoundException{
        String sPath = "C:\\Users\\owner\\Desktop\\Screen Shot\\";
        File filePath = new File(sPath);
        List<File> fileList = new ArrayList<File>();
        File[] files = filePath.listFiles();
        List<File> fileandFolderList = Arrays.asList(files);
        for (File file : fileandFolderList) {
            fileList.add(file);
            if (file.isDirectory()) {
                List<File> innerFileList = getFileList();
                fileList.addAll(innerFileList);
            }
        }

        return fileList;

    }

}

感谢您的时间。

2 个答案:

答案 0 :(得分:4)

您需要将getFileList搜索的根目录作为参数,并在每次递归时将子目录作为参数传递。 (目前,您在每次递归调用时都会从C:\Users\owner\Desktop\Screen Shot\开始。)

尝试以下操作(它在我的系统上按预期工作):

public class Test {

    public static void main(String[] args) {
        try {
            String root = "C:\\Users\\owner\\Desktop\\Screen Shot\\";
            List<File> files = getFileList(new File(root));
            for(File file : files ){
                System.out.println(file);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static List<File> getFileList(File filePath)
            throws FileNotFoundException{

        List<File> fileList = new ArrayList<File>();
        File[] files = filePath.listFiles();
        List<File> fileandFolderList = Arrays.asList(files);
        for (File file : fileandFolderList) {
            fileList.add(file);
            if (file.isDirectory()) {
                List<File> innerFileList = getFileList(file);
                fileList.addAll(innerFileList);
            }
        }

        return fileList;
    }
}

答案 1 :(得分:1)

我之前已经实现了类似你的方法,并且还得到了StackOverflowException,因为我没有检查File是否是符号链接。如果您在指向目录的符号链接上调用isDirectory,它将返回true。因此,您将遵循符号链接,它可以指向任何地方,可能导致无休止的树遍历,从而导致StackOverflowException。

相关问题