如何在Java中不递归地读取目录

问题描述

我正在尝试使用自己的对象来处理目录和文件。我需要打印目录名称及其内容以及其子目录的内容,直到堆栈为空。由于某种原因,我得到了一个空指针异常。这是我的代码。注释掉的代码代码可以使用但不是我自己的File对象的时候。我需要为此使用自己的对象。

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class DirInfo {
    
    String parentName = "";
    String childName = "";
    String fileName = "";
    
    public void readDirectory() throws IOException {
        DirInfo file = new DirInfo();
        ArrayBoundedStack<DirInfo> stack = new ArrayBoundedStack<DirInfo>();
        Scanner kb = new Scanner(system.in);
        System.out.println("Enter a directory to read.");
        //String dir = kb.next();
        parentName = kb.next();
        kb.close();
        
        stack.push(file);
        
        while (!stack.isEmpty()) {
            File currentDir = new File(parentName);
            DirInfo current = stack.top();
            //String parentName = current.getName();
            System.out.println(parentName);
            stack.pop();
            
            
            File [] files = currentDir.listFiles();
            
            for (File f : files) {
                if (f.isDirectory()) {
                    //stack.push(new File(current,f.getName()));
                    parentName = f.getName();
                    stack.push(new DirInfo());
                    //System.out.println("\t" + f.getName());
                    System.out.println("\t" + parentName);
                }
                else {
                    fileName = f.getName();
                    //System.out.println("\t" + f.getName());
                    System.out.println("\t" + fileName);
                }
            }
        }
    }
}

文件

import java.io.IOException;
public class DirectoryRead {

    public static void main(String[] args) throws IOException {
        DirInfo scan = new DirInfo();
        scan.readDirectory();
    }
}

输出

Enter a directory to read.
C:\\DirFolder1
C:\\DirFolder1
    DirFolder2
    Sample File1.txt
DirFolder2
Exception in thread "main" java.lang.NullPointerException
    at DirInfo.readDirectory(DirInfo.java:32)
    at DirectoryRead.main(DirectoryRead.java:7)

解决方法

您要在此处添加新的DirInfo

              stack.push(new DirInfo());

然后您尝试稍后再阅读

              File [] files = currentDir.listFiles();