- Java 编程示例
- 示例 - 主页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 多线程
- 示例 - 小程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- Java 有用资源
- Java - 快速指南
- Java - 有用资源
如何搜索 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
java_directories.htm
广告