Use Java to display code in a tree structure in text format

Source: Internet
Author: User

The Code is as follows. Output and use of various formats can be derived as needed.

Package test;

Import java. util. arraylist;
Import java. util. List;

Public class folder {
Public folder (String title ){
This. Title = title;
}

Private String title;

Private list <folder> Children = new arraylist <folder> ();

Public void addchild (Folder f ){
Children. Add (f );
}

Public list <folder> getchildren (){
Return children;
}

Public void setchildren (list <folder> Children ){
This. Children = children;
}

Public String gettitle (){
Return title;
}

Public void settitle (String title ){
This. Title = title;
}

Public String tostring (string lftstr, string append ){
Stringbuilder B = new stringbuilder ();
B. append (append + title );
B. append ("\ n ");
If (children. Size ()> 0 ){
For (INT I = 0; I <children. Size ()-1; I ++ ){
B. append (lftstr + children. Get (I). tostring (lftstr + "│", "success "));
}
B. append (lftstr + children. Get (children. Size ()-1). tostring (
Lftstr + "", "success "));

}
Return B. tostring ();

}

Public static void main (string [] ARGs ){
Folder root = new folder ("menu List ");
Folder F1 = new folder ("Start Menu ");
Root. addchild (F1 );
Folder f1_1 = new folder ("program ");
F1.addchild (f1_1 );
Folder f1_1_1 = new folder ("attachment ");
F00001.addchild (f00001_1 );
Folder f000000001_1 = new folder ("Entertainment ");
F000000001.addchild (f000000001_1 );
Folder f000000001_2 = new folder ("Entertainment 2 ");
F000000001.addchild (f000000001_2 );
Folder f1_2 = new folder ("auxiliary tool ");
F1.addchild (f1_2 );
Folder F2 = new folder ("My Documents ");
Root. addchild (F2 );
Folder F3 = new folder ("My documents2 ");
Root. addchild (F3 );

System. Out. println (root. tostring ("",""));
}
}

The running result is as follows:

Menu list
Renewal Start Menu
│ Program
│ Attachment
│ Entertainment
│ Vivo entertainment 2
│ Helper tools
My documents ents
Using my documents2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.