Home > Java > javaTutorial > body text

Java example - traverse all directories under the specified directory

黄舟
Release: 2017-02-13 10:22:15
Original
1354 people have browsed it

The following example demonstrates how to use the list method of the File class to traverse all directories under a specified directory:

/*
 author by w3cschool.cc
 Main.java
 */import java.io.*;class Main {
   public static void main(String[] args) {
      File dir = new File("F:");
      File[] files = dir.listFiles();
      FileFilter fileFilter = new FileFilter() {
         public boolean accept(File file) {
            return file.isDirectory();
         }
      };
      files = dir.listFiles(fileFilter);
      System.out.println(files.length);
      if (files.length == 0) {
         System.out.println("目录不存在或它不是一个目录");
      }
      else {
         for (int i=0; i< files.length; i++) {
            File filename = files[i];
            System.out.println(filename.toString());
         }
      }
   }}
Copy after login

The output result of running the above code is:

14F:\C Drive Data Old HDD
F:\Desktop1
F:\harsh
F:\hharsh finalF:\hhhh
F:\mov
F:\msdownld.tmp
F:\New FolderF:\ravi
F:\ravi3
F:\RECYCLER
F:\System Volume InformationF:\temp
F:\work
Copy after login

The above is Java Example - Traverse the contents of all directories under the specified directory. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template