提问人:Fernando Romo 提问时间:9/15/2023 最后编辑:Fernando Romo 更新时间:9/15/2023 访问量:13
如何在我的目录程序中显示文件(.txt、.pdf、.word 等)。爪哇岛
How do I display files (.txt, .pdfs, .word, etc) in my directory program. JAVA
问:
当我在程序上显示文件时,我无法显示目录中的文件并出现异常。我正在使用树状结构来尝试导入我的文件并显示它们。
Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because the return value of "java.io.File.listFiles()" is null at DirectoryTree.buildTree(DirectoryTree.java:21) at DirectoryTree.buildTree(DirectoryTree.java:27) at DirectoryTree.main(DirectoryTree.java:53)
import java.io.*;
class TreeNode {
String name;
TreeNode[] children;
//Constructor
TreeNode(String name, int numChildren) {
this.name = name;
children = new TreeNode[numChildren];
}
}
public class DirectoryTree {
public static TreeNode buildTree(String path) {
File file = new File(path);
//if a file exists return null
if (!file.exists()) {
return null;
}
TreeNode root = new TreeNode(file.getName(), file.listFiles().length);
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (int i = 0; i < children.length; i++) {
root.children[i] = buildTree(children[i].getAbsolutePath());
}
}
}
return root;
}
public static void displayTree(TreeNode node, String indent) {
System.out.println(indent + node.name);
if (node.children != null) {
for (TreeNode child : node.children) {
if (child != null) {
displayTree(child, indent + "|---");
}
}
}
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("To run this program you must use the terminal and read the README file for instructions.");
System.exit(1);
}
String path = args[0];
TreeNode tree = buildTree(path);
if (tree != null) {
displayTree(tree, "");
} else {
System.out.println("Invalid directory path or DNE.");
}
}
}
我已经尝试了目录中的多个文件,但它没有显示。无论我向目录中添加什么文件,我总是会得到豁免。它显示root_directory和sub_directories,但只要目录中有一个文件,就会出现异常。
答: 暂无答案
评论