我是java开发的新手 我试图显示系统的所有驱动器,包括所有文件和文件夹。 此代码工作正常,但只显示单个目录或驱动器。 我怎样才能让它显示我系统上的所有驱动器,包括文件夹和文件。 提前谢谢。
///显示特定目录的实现(目前使用netbeans)
jTree1.setModel(new FileSystemModel(new File("Director Path to display")));
// FileSystemModel
public class FileSystemModel implements TreeModel {
private File root;
private Vector listeners = new Vector();
public FileSystemModel(File rootDirectory)
{
root = rootDirectory;
}
@Override
public Object getRoot() {
return root;
}
@Override
public Object getChild(Object parent, int index) {
File directory = (File) parent;
String[] children = directory.list();
return new FileSystemModel.TreeFile(directory, children[index]);
}
@Override
public int getChildCount(Object parent) {
File file = (File) parent;
if (file.isDirectory()) {
String[] fileList = file.list();
if (fileList != null) {
return file.list().length;
}
}
return 0;
}
@Override
public boolean isLeaf(Object node) {
File file = (File) node;
return file.isFile();
}
@Override
public int getIndexOfChild(Object parent, Object child) {
File directory = (File) parent;
File file = (File) child;
String[] children = directory.list();
for (int i = 0; i < children.length; i++) {
if (file.getName().equals(children[i])) {
return i;
}
}
return -1;
}
@Override
public void valueForPathChanged(TreePath path, Object value) {
File oldFile = (File) path.getLastPathComponent();
String fileParentPath = oldFile.getParent();
String newFileName = (String) value;
File targetFile = new File(fileParentPath, newFileName);
oldFile.renameTo(targetFile);
File parent = new File(fileParentPath);
int[] changedChildrenIndices = {getIndexOfChild(parent, targetFile)};
Object[] changedChildren = {targetFile};
fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);
}
private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
Iterator iterator = listeners.iterator();
TreeModelListener listener = null;
while (iterator.hasNext()) {
listener = (TreeModelListener) iterator.next();
listener.treeNodesChanged(event);
}
}
@Override
public void addTreeModelListener(TreeModelListener listener) {
listeners.add(listener);
}
@Override
public void removeTreeModelListener(TreeModelListener listener) {
listeners.remove(listener);
}
private class TreeFile extends File {
public TreeFile(File parent, String child) {
super(parent, child);
}
@Override
public String toString() {
return getName();
}
}
}
答案 0 :(得分:0)
要查找整个树,您需要识别其中一个子项本身是一个目录并收集其内容。看起来你想要在你调用的方法getChild
中做到这一点(getChildren将是一个更好的名字)。