Javaexamples-dir-search
提供:Dev Guides
Javaの例-ファイルの検索
問題の説明
ディレクトリ内のすべてのファイルを検索する方法は?
溶液
次の例は、Fileクラスのdir.list()メソッドを使用して、指定したディレクトリの下にあるすべてのファイルのリストを検索および取得する方法を示しています。
import java.io.File;
public class Main {
public static void main(String[] argv) throws Exception {
File dir = new File("directoryName");
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);
}
}
}
}
結果
上記のコードサンプルは、次の結果を生成します。
sdk
---vehicles
------body.txt
------color.txt
------engine.txt
---ships
------shipengine.txt
以下は、Javaのディレクトリ内のすべてのファイルを検索する別のサンプル例です。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
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:\bootmgr
C:\BOOTNXT
C:\hiberfil.sys
C:\pagefile.sys
C:\recovery.img.img
C:\swapfile.sys