IO Note Sixth simple folder and file directory query

Source: Internet
Author: User

File directory Query

Returns a file array using the Listfiles () method in the file class. has used a recursive search combined with isdirectory () to make a critical point. You can enter a multilevel directory query and then use a StringBuilder append method to get the file directory to return its ToString function to return the file directory name. The Append method of StringBuilder here is because if you use string+=, you will consume memory. This method is faster, but not for multi-threading, and it is recommended to use StringBuffer if such synchronization is required. The effect is as shown in the figure:

The implementation code is as follows:

Package Cn.hncu.io3;

Import Java.io.File;

public class ShowDir2 {public
	static void Main (string[] args) {
		file Dir=new file ("E:/bcde");
		Showdir (dir,0);
	}

	private static void Showdir (File dir,int count) {
		System.out.println (Getspace (count) +dir.getname ());
		count++;
		File files[]=dir.listfiles ();
		if (files!=null) {for
			(File f:files) {
				if (f.isdirectory ()) {
					showdir (f,count);
				} else{
					System.out.println (Getspace (count) +f.getname ());

	}}} private static String getspace (int count) {
		StringBuilder sb=new StringBuilder ();
		for (int i = 0; i < count; i++) {
			sb.append ("|--"),/////////With sb+= memory, this addition is a bit better
		}
		return sb.tostring ();
	}

}


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.