62,615
社区成员
发帖
与我相关
我的任务
分享
public class Hierarchy {
static class Node {
private String name;
private List<Node> nodeList;
public Node(String name) {
this.name = name;
nodeList = new ArrayList<Node>();
}
public Node getSubNode(String name) {
for (Node subNode : nodeList) {
if (subNode.getName().equals(name))
return subNode;
}
return null;
}
public String getName() {
return name;
}
public void addSubNode(Node subNode) {
nodeList.add(subNode);
}
public void print(){
printNode(this, "+");
}
private void printNode(Node node, String prefix){
System.out.println(prefix + node.getName());
prefix += "---";
for(Node subNode : node.nodeList){
printNode(subNode, prefix);
}
}
}
private Node root;
public Hierarchy() {
}
public void addNode(String path) {
String[] nodeNames = path.split("\r\n");
Node currentNode = null;
for(String nodeName : nodeNames){
currentNode = addNodeIfNotExist(nodeName, currentNode);
}
}
public void print(){
if(root != null)
root.print();
else
System.out.println("empty");
}
public Node addNodeIfNotExist(String name, Node parent){
if(parent == null){
if(root == null){
root = new Node(name);
return root;
}else if(root.getName().equals(name))
return root;
else
throw new IllegalArgumentException("输入了一个不同的根节点");
}else{
Node targetNode = parent.getSubNode(name);
if(targetNode == null){
targetNode = new Node(name);
parent.addSubNode(targetNode);
}
return targetNode;
}
}
public static void main(String[] args) {
String input = "a\r\n +---b\r\n +----c\r\na\r\n +---c\r\na\r\n +---b\r\n +----d";
String[] paths = input.split("(?m)^(?=\\S)");
Hierarchy hierarchy = new Hierarchy();
for(String path : paths){
if(path.length() > 0)
hierarchy.addNode(path.replaceAll("([^a-z\r\n]*)", ""));
}
hierarchy.print();
}
}
试试这个合你要求不,估计有bug,没怎么检查
import java.io.*;
public class ListFiles{
public static void main(String[] args){
File f = new File("a");
System.out.println(f.getName());
tree(f,0);
}
private static void tree(File f,int level){
String preStr = "";
for(int i=0;i<=level;i++){
preStr += " +---";
}
File[] childs = f.listFiles();
for(int i=0;i<childs.length;i++){
System.out.println(preStr + childs[i].getName());
if(childs[i].isDirectory()){
tree(childs[i],level + 1);
}
}
}
}