gpt4 book ai didi

java - Java获取目录下所有文件的程序

转载 作者:搜寻专家 更新时间:2023-10-31 08:21:27 25 4
gpt4 key购买 nike

我正在开发这个程序来获取目录中的所有文件。出于某种原因,我在第 16 行收到 NullPointerException。我不知道为什么,因为这是一个似乎在类里面与我们的老师一起工作的模板。谢谢。

import java.util.*;
import java.io.*;

public class FindDirectories {
public static void main(String[] args) {
if (args.length == 0) {
args = new String[] { ".." };
}

List<String> nextDir = new ArrayList<String>();
nextDir.add(args[0]); // either the one file, or the directory
try {
while(nextDir.size() > 0) { // size() is num of elements in List
File pathName = new File(nextDir.get(0)); // gets the element at the index of the List
String[] fileNames = pathName.list(); // lists all files in the directory
for(int i = 0; i < fileNames.length; i++) {
File f = new File(pathName.getPath(), fileNames[i]); // getPath converts abstract path to path in String,
// constructor creates new File object with fileName name
if (f.isDirectory()) {
System.out.println(f.getCanonicalPath());
nextDir.add(f.getPath());
}
else {
System.out.println(f);
}
}
nextDir.remove(0);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}

最佳答案

查看 Javadoc for File.list() .具体来说:

Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

在您的代码中 pathName.list(); 必须返回 null,因此 pathName 不代表有效目录,或者在尝试获取列表时发生 IO 错误该目录中的文件。

关于java - Java获取目录下所有文件的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3332486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com