我正在开发一个程序,在该程序中我已经勾画出带有文件系统的通用树的粗略轮廓。我有一个名为 File
的类,并且有 2 个扩展 File 的类,分别是 Directory
和 TextFile
。在我的 FileSystem 类中,我有一个存储根的变量。我很确定由于我创建 FileSystem
类的原因,我收到了 NullPointerException,但我不知道如何修复它。
这是我的文件类:
public abstract class File {
private String name;
private Directory parent;
public File(String name) {
this.name = name;
}
Directory getParent() {
return parent;
}
String getName() {
return name;
}
void setParent(Directory parent) {
this.parent = parent;
}
String getPath() {
return getPath(this);
}
String getPath(File f) {
if (f == FileSystem.getRoot()) {
return "";
} else {
return getPath(f.parent) + "/" + f.name;
}
}
}
这是我的目录类:
import java.util.ArrayList;
public class Directory extends File {
private ArrayList<File> children = new ArrayList<File>();
Directory(String name){
super(name);
}
void addChild(File f){
setParent(this);
children.add(f);
}
ArrayList<File> getChildren(){
return children;
}
}
这是我的文件系统类:
public class FileSystem {
static Directory root;
//Constructor
public FileSystem(){
}
//Constructor with parameters
public FileSystem(Directory root){
this.root = root;
}
public static File getRoot(){
return root;
}
}
这是我在主要方法中尝试做的事情:
//Creating root directory
Directory root = new Directory("/");
//Creating FileSystem user will add and remove directories/text files from
FileSystem tree = new FileSystem(root);
Directory a = new Directory("a");
Directory b = new Directory("b");
Directory c = new Directory("c");
root.addChild(a);
a.addChild(b);
b.addChild(c);
c.getPath();
任何有关如何追踪我的路径的帮助将不胜感激。我希望它打印出以下内容:/a/b/c
最佳答案
我认为问题可能出在这个方法中:
void addChild(File f){
setParent(this); //seting parent for directory not for file which is passed
children.add(f);
}
尝试更改为:
f.setParent(this)
关于java - 递归方法中的NullPointer(获取通用树路径),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34146435/