Java如何列出目錄中的所有檔案?

2019-10-16 22:29:45

在Java程式中,如何搜尋(列出)目錄中的所有檔案?

以下範例說明如何使用File類的dir.list()方法搜尋並獲取指定目錄下的所有檔案的列表。

package com.yiibai;

import java.io.File;

public class SearchingFiles {
    public static void main(String[] argv) throws Exception {
        File dir = new File("F:\\worksp\\javaexamples\\java_directories");
        String[] children = dir.list();

        if (children == null) {
            System.out.println("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);
            }
        }
    }
}

執行上面範例程式碼,得到以下結果 -

.classpath
.project
bin
dir11
myfile.txt
src

範例-2

以下是Java中列出目錄中的所有檔案的另一個範例。

package com.yiibai;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class SearchingFiles2 {
    public static void main(String[] args) throws IOException {
        System.out.println("Enter the path to folder to search for files=> ");
        Scanner s1 = new Scanner(System.in);
        String folderPath = s1.next();
        File folder = new File(folderPath);

        if (folder.isDirectory()) {
            File[] listOfFiles = folder.listFiles();
            if (listOfFiles.length < 1)
                System.out.println("There is no File inside Folder");
            else
                System.out.println("List of Files & Folder");
            for (File file : listOfFiles) {
                if (!file.isDirectory())
                    System.out.println(file.getCanonicalPath().toString());
            }
        } else
            System.out.println("There is no Folder @ given path :" + folderPath);
    }
}

執行上面範例程式碼,得到以下結果 -

Enter the path to folder to search for files => 
c:\
List of Files & Folder
C:\.rnd
C:\AVScanner.ini
C:\bootmgr
C:\BOOTNXT
C:\BOOTSECT.BAK
C:\DriverName.cfg
C:\file-for-download.txt
C:\grldr
C:\grldr.bak
C:\HaxLogs.txt
C:\LibAntiPrtSc_ERROR.log
C:\LibAntiPrtSc_INFORMATION.log
C:\okldr
C:\okldr.mbr
C:\report.rpt
C:\SecurityScanner.dll
C:\setup.log
C:\setupinfidb.db
C:\swapfile.sys
C:\Uninstall