1.效果图:在控制台输出所有的文件的文件名如下:

Java读取指定目录下的所有文件名_java

2.FileUtil.java:

package cn.gov.csrc.base.report.util;

import java.io.File;
import java.util.ArrayList;

public class FileUtil {

/**
* 获取指定目录下的所有文件名
*
* @param obj
* @return
*/
public static ArrayList<File> getListFiles(Object obj) {
File directory = null;
if (obj instanceof File) {
directory = (File) obj;
} else {
directory = new File(obj.toString());
}
ArrayList<File> files = new ArrayList<File>();
if (directory.isFile()) {
files.add(directory);
return files;
} else if (directory.isDirectory()) {
File[] fileArr = directory.listFiles();
for (int i = 0; i < fileArr.length; i++) {
File fileOne = fileArr[i];
files.addAll(getListFiles(fileOne));
}
}
return files;
}

public static void main(String[] args) {
String path = "D://jubao//send";
ArrayList<File> list = FileUtil.getListFiles(path);
for (File file : list) {
System.out.println(file.getName());
}
}
}