Java 示例 - 显示目录中的文件

  • 问题描述

    如何显示目录中的所有文件?
  • 解决方案

    以下示例显示如何使用 File 类的 list 方法显示目录中包含的所有文件。
    
    import java.io.*;
    public class Main {
       public static void main(String[] args) {
          File dir = new File("C:");
          String[] children = dir.list();
          
          if (children == null) {
             System.out.println( "Either dir does not exist or is not a directory");
          } else { 
             for (int i = 0; i< children.length; i++) {
                String filename = children[i];
                System.out.println(filename);
             }
          }
       }
    }
    
  • 结果

    上面的代码示例将产生以下结果。
    
    build
    build.xml
    destnfile
    detnfile
    filename
    manifest.mf
    nbproject
    outfilename
    src
    srcfile
    test
    
    以下是显示目录中所有文件的另一个示例。
    
    import java.io.File;
    public class ReadFiles { 
       public static File folder = new File("C:\\Apache24\\htdocs");
       static String temp = "";
       
       public static void main(String[] args) {
          System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
          listFilesForFolder(folder);
       } 
       public static void listFilesForFolder(final File folder) {
          for (final File fileEntry : folder.listFiles()) {
             if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
             } else {
                if (fileEntry.isFile()) {
                   temp = fileEntry.getName();
                   if ((temp.substring(temp.lastIndexOf('.') 
                      + 1, temp.length()).toLowerCase()).equals("txt"))System.out.println(
                      "File = " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
                } 
             } 
          } 
       }
    }
    
    上面的代码示例将产生以下结果。
    
    Reading files under the folder C:\Apache24\htdocs
    File= C:\Apache24\htdocs\android\bkp\end.txt
    File= C:\Apache24\htdocs\android\end.txt
    File= C:\Apache24\htdocs\cpp_standard_library\images\code.txt
    File= C:\Apache24\htdocs\java\Java - Data Structures.txt
    File= C:\Apache24\htdocs\java\Java - Inheritance.txt
    File= C:\Apache24\htdocs\scripts\easyui\changelog.txt