JAVA traverse all files under a folder

Source: Internet
Author: User

All files under the JAVA Traversal folder (recursive calls and non-recursive calls)

1. Do not use recursive method calls.

PublicvoidTraverseFolder1 (String path) {int filenum = 0, Foldernum = 0; File File =NewFile (path);If(File.exists ()) {linkedlist<file> list =New linkedlist<file>(); file[] Files =File.listfiles ();For(File file2:files) {If(File2.isdirectory ()) {System.out.println ("folder:" +File2.getabsolutepath ()); List.add (file2); foldenum++; }Else{System.out.println ("File:" +File2.getabsolutepath ()); filenum++; }} File Temp_file;while (!List.isEmpty ()) {temp_file = List.removefirst (); files = Temp_file.listfiles (); Span style= "color: #0000ff;" >forif  (File2.isdirectory ()) {System.out.println ("folder:" +else File2.getabsolutepath ()); Filenum++else); } System.out.println ("folder total:" + foldernum + ", file total:" + FileNum);}    

2. Use recursive method calls.

PublicvoidTraverseFolder2 (String path) {File File =NewFile (path);If(File.exists ()) {file[] files =File.listfiles ();if (files.length = = 0); returnelse {for (File file2:files) {if (File2.isdirectory ()) { System.out.println ("folder:" + File2.getabsolutepath ()); TraverseFolder2 (File2.getabsolutepath ()); } else File2.getabsolutepath ()); }}}} else); } } 

3,

PublicStatic list<file>Getfilelist (String strpath) {File dir =NewFile (strpath); file[] files = dir.listfiles ();//All the files in the file directory are put into the arrayif (Files! =Null) {for (int i = 0; i < files.length; i++) {String FileName = Files[i].getname (); if (Files[i].isdirectory ()) {// Determine whether the file or folder Getfilelist (Files[i].getabsolutepath ()); // Get file absolute path} else if (Filename.endswith ("avi")) {// Determine if the file name ends with an. avi String strfilename = Files[i].getabsolutepath (); SYSTEM.OUT.PRINTLN ("---" + strFileName); Filelist.add (Files[i]);} else {continuereturn FileList;}           

JAVA traverse all files under a folder

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.