java , how to get all the files in the specified directory?
Look at the code:
- /***
- * Get all files (excluding folders) in the specified directory, using recursion
- *
- * @param obj
- * @return
- */
- publicstatic 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;
- } elseif (directory.isDirectory()) {
- File[] fileArr = directory.listFiles();
- for (int i = 0; i < fileArr.length; i++) {
- File fileOne = fileArr[i];
- files.addAll(getListFiles(fileOne));
- }
- }
- return files;
- }
Note: The above method uses recursion , so it includes files in subdirectories under subdirectories. . .
Test code:
- @Test
- publicvoid test_getListFiles(){
- ArrayList<File> files=FileUtils.getListFiles("d:\\Temp\\a\\a");
- SystemUtil.printFilesFilePath(files);
- }
Output result:
d:\Temp\a\a\divided\merged\oracle study notes.doc
d:\Temp\a\a\divided\oracle study notes.doc_1_3kldv
d:\Temp\a\a\divided\oracle study notes.doc_2_3kldv
d:\Temp\a\a\divided\oracle study notes.doc_3_3kldv
d:\Temp\a\a\oracle study notes.doc
Filter prefix ( just get files in the specified directory, no recursion ):
- /***
- *
- * @param path
- * @param prefixStr
- * : prefix name
- * @return
- */
- publicstatic File[] getFilesByPathPrefix(File path, final String prefixStr) {
- File[] fileArr = path.listFiles(new FilenameFilter() {
- @Override
- publicboolean accept(File dir, String name) {
- // System.out.println("prefixStr:"+prefixStr);
- if ((ValueWidget.isNullOrEmpty(prefixStr) || (dir.isDirectory() && name
- .startsWith(prefixStr)))) {
- returntrue;
- } else {
- return false;
- }
- }
- });
- return fileArr;
- }
- /***
- * 前缀名
- *
- * @param pathStr
- * @param prefixStr
- * @return
- */
- public static File[] getFilesByPathAndPrefix(String pathStr,
- final String prefixStr) {
- File path = new File(pathStr);
- return getFilesByPathPrefix(path, prefixStr);
- }
过滤后缀名(只是获取指定目录下的文件,没有递归):
- /***
- *
- * @param path
- * @param prefixStr
- * :后缀名
- * @return
- */
- public static File[] getFilesByPathAndSuffix(File path,
- final String sufixStr) {
- File[] fileArr = path.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- // System.out.println("prefixStr:"+prefixStr);
- if ((ValueWidget.isNullOrEmpty(sufixStr) || (dir.isDirectory() && name
- .endsWith(sufixStr)))) {
- return true;
- } else {
- return false;
- }
- }
- });
- return fileArr;
- }
- /***
- * 后缀名
- *
- * @param pathStr
- * @param sufixStr
- * @return
- */
- public static File[] getFilesByPathAndSuffix(String pathStr,
- final String sufixStr) {
- File path = new File(pathStr);
- return getFilesByPathAndSuffix(path, sufixStr);
- }
Reprinted from: http://hw1287789687.iteye.com/blog/1946488