- Non-recursive way to get all files in a directory and its subdirectories in Java
- 3 Answers 3
- list all files from directories and subdirectories in Java
- 6 Answers 6
- list all files in the folder and also sub folders [duplicate]
- 3 Answers 3
- Program to get all files within a directory in Java
- 5 Answers 5
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
Non-recursive way to get all files in a directory and its subdirectories in Java
I am trying to get a list of all files in a directory and its subdirectories. My current recursive approach is as follows:
private void printFiles(File dir) < for (File child : dir.listFiles()) < if (child.isDirectory()) < printFiles(child); >else if (child.isFile()) < System.out.println(child.getPath()); >> > printFiles(new File("somedir/somedir2"));
However, I was hoping there was a non-recursive way (an existing API call, maybe) of doing this. If not, is this the cleanest way of doing this?
possible duplicate of Recursively list files in Java. The title says recursively, but the first answer is a library call.
@cularis Not a duplicate, as I’m trying to do it non-recursively, whereas the other SO question is asking for it to be done recursively.
What’s wrong with recursion? There’s no API for this, however you can still do it with a while loop and some funny other business, but it will be messy.
Either way, I do believe this question provides value to the community as someone searching for it, at first glance, will ignore the other question (like I did) because of the title
3 Answers 3
You can always replace a recursive solution with an iterative one by using a stack (for DFS) or a Queue (For BFS):
private void printFiles(File dir) < Stackstack = new Stack(); stack.push(dir); while(!stack.isEmpty()) < File child = stack.pop(); if (child.isDirectory()) < for(File f : child.listFiles()) stack.push(f); >else if (child.isFile()) < System.out.println(child.getPath()); >> > printFiles(new File("abc/def.ghi"));
Sometimes I dislike how long it takes for Eclipse to start. Well done. I am very surprised at why some engineers would wonder why recursion can be bad, and why using a Stack would of been messy.
How is the stack approach better? Sure it might be a little faster but recursion is very simple and elegant. Internally, recursion uses a stack anyways.
Both, speed, and the fact that recursion has to store the state of the entire function (which has been stripped down in my question for the purpose of posting it on SO) on the stack, whereas with this approach, I am only saving the File objects on the stack
Hey this is perfect, can we restrict tht it goes only to depth 2 or 5. like some number not more than that.
Java 8 onward, you can use Files#walk to list out all files and directories recursively in a given directory. Further you can apply the filter like Files::isRegularFile to filter out the directories if you need only regular files.
On the flip side, if you only need to list the given directory but not its sub-directories, you can use the lazy method Files#list which will only give you the files and directories in the given directory. You can again further apply the filter mentioned above.
FileUtils Is probably the best way to go. (COPY OF THE LINKED QUESTION) only posted so people searching this will see it and will probably not read the comments
edit: Methods to be used Listfiles
Maybe I’m missing something, but I was looking at the FileUtils documentation, and there’s a note under the constructor which says «Instances should NOT be constructed in standard programming.»
Ran into another issue; Eclipse doesn’t recognize the FileUtils class. Which package should I be importing?
Ahh, looks like I can’t use it after all. Don’t have the option of installing additional libraries. But thanks anyway!
It’s a part of a Distributed File System assignment for school, and the machines the code will be tested on does not have the apache commons library installed.
list all files from directories and subdirectories in Java
What would be the fastest way to list the names of files from 1000+ directories and sub-directories? EDIT; The current code I use is:
import java.io.File; public class DirectoryReader < static int spc_count=-1; static void Process(File aFile) < spc_count++; String spcs = ""; for (int i = 0; i < spc_count; i++) spcs += " "; if(aFile.isFile()) System.out.println(spcs + "[FILE] " + aFile.getName()); else if (aFile.isDirectory()) < System.out.println(spcs + "[DIR] " + aFile.getName()); File[] listOfFiles = aFile.listFiles(); if(listOfFiles!=null) < for (int i = 0; i < listOfFiles.length; i++) Process(listOfFiles[i]); >else < System.out.println(spcs + " [ACCESS DENIED]"); >> spc_count--; > public static void main(String[] args) < String nam = "D:/"; File aFile = new File(nam); Process(aFile); >>
What do you mean by fastest? simplest to code, best performing on a certain OS, or best performing for certain directory structures?
6 Answers 6
As this answer shows up on top of google, i’m adding a java 7 nio solution for listing all files and directories, it is takes about 80% less time on my system.
try < Path startPath = Paths.get("c:/"); Files.walkFileTree(startPath, new SimpleFileVisitor() < @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) < System.out.println("Dir: " + dir.toString()); return FileVisitResult.CONTINUE; >@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) < System.out.println("File: " + file.toString()); return FileVisitResult.CONTINUE; >@Override public FileVisitResult visitFileFailed(Path file, IOException e) < return FileVisitResult.CONTINUE; >>); > catch (IOException e)
list all files in the folder and also sub folders [duplicate]
How can i return a file array that include all files on the folder and also sub folders my method just work for folder and it doesn’t include sub folders .
public File[] listf(String directoryName) < // . list file File directory = new File(directoryName); // get all the files from a directory File[] fList = directory.listFiles(); for (File file : fList) < if (file.isFile()) < System.out.println(file.getAbsolutePath()); >else if (file.isDirectory()) < listf(file.getAbsolutePath()); >> System.out.println(fList); return fList; >
3 Answers 3
Using you current code, make this tweak:
public void listf(String directoryName, List files) < File directory = new File(directoryName); // Get all files from a directory. File[] fList = directory.listFiles(); if(fList != null) for (File file : fList) < if (file.isFile()) < files.add(file); >else if (file.isDirectory()) < listf(file.getAbsolutePath(), files); >> >
listFiles public static Collection listFiles(File directory, String[] extensions, boolean recursive) Finds files within a given directory (and optionally its subdirectories) which match an array of extensions. Parameters: directory - the directory to search in extensions - an array of extensions, ex. . If this parameter is null, all files are returned. recursive - if true all subdirectories are searched as well Returns: an collection of java.io.File with the matching files
You can return a List instead of an array and things gets much simpler.
public static List listf(String directoryName) < File directory = new File(directoryName); ListresultList = new ArrayList(); // get all the files from a directory File[] fList = directory.listFiles(); resultList.addAll(Arrays.asList(fList)); for (File file : fList) < if (file.isFile()) < System.out.println(file.getAbsolutePath()); >else if (file.isDirectory()) < resultList.addAll(listf(file.getAbsolutePath())); >> //System.out.println(fList); return resultList; >
Why? I mean: what is your problem and why would you want to avoid using lists which are doing all the merging for you?
This is okay to recursively return files and directories within that specified directory. And as the question (even though its a duplicate) is asking how to return (only) files from the provided directory and files within all sub-directories you may have to change the codes a little bit: //resultList.addAll(Arrays.asList(fList)); for (File file : fList) < if (file.isFile()) < resultList.add(file); >else if (file.isDirectory()) < resultList.addAll(listf(file.getAbsolutePath())); >>
Program to get all files within a directory in Java
I’m working on this program to get all the files in the directory. For some reason I am getting a NullPointerException on Line 16. I don’t know why though since this is a template that seemed to work in class with our teacher. Thanks.
import java.util.*; import java.io.*; public class FindDirectories < public static void main(String[] args) < if (args.length == 0) < args = new String[] < ".." >; > List nextDir = new ArrayList(); nextDir.add(args[0]); // either the one file, or the directory try < while(nextDir.size() >0) < // size() is num of elements in List File pathName = new File(nextDir.get(0)); // gets the element at the index of the List String[] fileNames = pathName.list(); // lists all files in the directory for(int i = 0; i < fileNames.length; i++) < File f = new File(pathName.getPath(), fileNames[i]); // getPath converts abstract path to path in String, // constructor creates new File object with fileName name if (f.isDirectory()) < System.out.println(f.getCanonicalPath()); nextDir.add(f.getPath()); >else < System.out.println(f); >> nextDir.remove(0); > > catch(IOException e) < e.printStackTrace(); >> >
5 Answers 5
Check out the Javadoc for File.list() . Specifically:
Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
In your code pathName.list(); must be returning null so pathName does not represent a valid directory, or an IO error occurred trying to get a list of files from that directory.
Yes @Crystal, you should test for that. Then decide what to do when this happens: report error, prompt user for correct dir etc.
Use bellow snippet to get all the files from all the sub directories:
import java.io.File; /** * * @author santoshk */ public class ListFiles < File mainFolder = new File("F:\\personal"); public static void main(String[] args) < ListFiles lf = new ListFiles(); lf.getFiles(lf.mainFolder); >public void getFiles(File f) < File files[]; if(f.isFile()) System.out.println(f.getAbsolutePath()); else< files = f.listFiles(); for (int i = 0; i < files.length; i++) < getFiles(files[i]); >> > >
If you’re getting a NullPointerException on line 16, it must mean that fileNames is null, so fileNames.length is invalid. Take a look at the javadoc for File.list and you’ll see that pathName.list() can be null if pathName is not a directory, or if an exception occurs. So you’ll just need to check whether fileNames is null before trying to use it.
import java.io.File; import java.util.ArrayList; import java.util.LinkedList; public class FileEnumerator < /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException < // Prepare the List of files String path = "C:/"; ArrayListFiles = new ArrayList(); LinkedList Dir = new LinkedList(); File f = new File(path); Dir.add(f.getAbsolutePath()); while(!Dir.isEmpty()) < f = new File(Dir.pop()); if(f.isFile()) < Files.add(f.getAbsolutePath()); >else < String arr[] = f.list(); try < for(int i = 0;i> catch(NullPointerException exp) < Dir.remove(f.getAbsoluteFile()); >> > //Print the files for(int i = 0;i > >
I think this code should work well. Although I have tested it just on Windows. But other OS will need at most small changes.
«I think this code should work well. Although I have tested it just on Windows. But other OS will need at most small changes.» Given that good Java code should run on other OS with no changes, the code in your answer is not a good example. At the very least it should use either System.getProperty(«file.separator») or the File constructor that accepts path/name arguments instead of / . Then we might go into using String objects to represent File s. Presuming a C: drive rather than accepting a command line arg. (. )
import java.io.*; public class filedir < public static void main(String[] args) < try< Files f = new File("C:\\");//the path required String a[]; a=f.list(); for (int i = 0; i > catch(Exception e) < System.err.println(e); >> >
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.