How can I read all files in a folder from Java?
Asked Answered
F

35

790

How can I read all the files in a folder through Java? It doesn't matter which API.

Fumigator answered 4/12, 2009 at 3:39 Comment(5)
I agree, point out the class to use so the poster can become familiar with the various method, otherwise the poster doesn't bother to read the API to find out what other methods are available.Softpedal
Did you mean all files in a folder, or all files in a folder and all subfolders?Cornerstone
An up to date link to the API: docs.oracle.com/javase/7/docs/api/java/io/File.htmlElectrum
If you are using Java 7 or newer you can use Files.walkFileTree, see https://mcmap.net/q/53865/-how-can-i-read-all-files-in-a-folder-from-javaStamin
The majority of the answers are just code dumps (without any explanation whatsoever). Are they all completely bogus answers?Improvised
E
1140

Use:

public void listFilesForFolder(final File folder) {
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
        } else {
            System.out.println(fileEntry.getName());
        }
    }
}

final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);

The Files.walk API is available from Java 8.

try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
    paths
        .filter(Files::isRegularFile)
        .forEach(System.out::println);
} 

The example uses the try-with-resources pattern recommended in the API guide. It ensures that no matter circumstances, the stream will be closed.

Extortionary answered 4/12, 2009 at 11:21 Comment(8)
getName() will only give the name of the file in its directory, which could be a subdirectory of the original. If you plan to use this information to find the files, you may find the path given by getPath() to be more useful.Sinkage
Can I use this method to find all files of a specific type say pdf or html across my whole system? My concern is efficiency, is it fast enough to be used for systems with thousands of files or is there a better alternative?Bacteriophage
@codeln As of Java 8, the performance is very acceptable, you don't notice anything laggy about it. It's fast, efficient, and readable enough to get your job done.Velasco
In Java 8 you can also make use of the filter method. Then forEach is not longer needed. See here -> https://mcmap.net/q/53865/-how-can-i-read-all-files-in-a-folder-from-javaJaundiced
What is the purpose of declaring the File objects final?Alithea
Just to indicate it's only initialised once.Extortionary
Let's not forget the import here for those who get a NoClassDefFoundError on the File object. import java.io.File;Guimpe
I would only mention simple detail regarding to Files.walk() throws IOException, so the bottom example should contain the catch clause.Iridium
V
219
File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();

for (File file : listOfFiles) {
    if (file.isFile()) {
        System.out.println(file.getName());
    }
}
Vetchling answered 4/12, 2009 at 3:41 Comment(3)
I think this will print the directory names, and no filenamesStarlin
By far easier to understand than accepted answer. +1.Bickart
@Bickart Because this doesn't read all files in the directory, it only gets the files directly inside the given directory. If the given directory itself contains other directories, their content won't be readHelicon
J
172

In Java 8 you can do this

Files.walk(Paths.get("/path/to/folder"))
     .filter(Files::isRegularFile)
     .forEach(System.out::println);

which will print all files in a folder while excluding all directories. If you need a list, the following will do:

Files.walk(Paths.get("/path/to/folder"))
     .filter(Files::isRegularFile)
     .collect(Collectors.toList())

If you want to return List<File> instead of List<Path> just map it:

List<File> filesInFolder = Files.walk(Paths.get("/path/to/folder"))
                                .filter(Files::isRegularFile)
                                .map(Path::toFile)
                                .collect(Collectors.toList());

You also need to make sure to close the stream! Otherwise you might run into an exception telling you that too many files are open. Read here for more information.

Jaundiced answered 6/10, 2014 at 12:8 Comment(14)
Getting an error with .map(Path::toFile) Also .forEach(path -> System.out.println(path.toString()); should be .forEach(path -> System.out.println(path.toString()));Expulsive
Thanks for the correction. What error do you get? I execute the exact code in a project of mine and do not get an error.Jaundiced
It says "Invalid method reference, cannot find symbol" "Method toFile" is toFile supposed to be something else?Expulsive
Can u please paste your code in a PasteBin? Are you using java.nio.file.Path? I just checked the method toFile() should exist even prior to java 8 -> docs.oracle.com/javase/7/docs/api/java/nio/file/…Jaundiced
I had the same problem, but automatic imports imported something else, not the java.nio.file.Path.Correctitude
and to apply a filename filter (like by extension, using String.endsWith()) after that is extremely easy too, thanks!Demark
Looks like your Java compiler is set to 1.7. Bump it up to 1.8 and/or install new version of your IDE.Dowling
@JulianLiebl how do we skip hidden files? filter(Files::isHidden) doesn't work. The error says: "Unhandled exception type IOException", but the method already throws IOException.Kentonkentucky
@NadjibMami Please have a look here: razem.io/blog/posts/year2015/0819_try_catch_lambda Was to compilcated to answer in a comment. So I wrote a quick blog post.Jaundiced
@JulianLiebl Whow, this is cool. Thanks for your effort, it really helps!Kentonkentucky
You could write the forEach as .forEach(System.out::println). Also the .collect(Collectors.toList()) is not needed in your first example.Crackbrain
@Crackbrain I updated the answer to address your concerns.Jaundiced
If anyone is still looking for the try catch lambda topic the url of my blog has been changed -> razem.io/blog/y2015/0819_try_catch_lambda.htmlJaundiced
How do you close the stream when your code is like the second example code: List<File> filesInFolder = Files.walk(Paths.get("/path/to/folder")) .filter(Files::isRegularFile) .map(Path::toFile) .collect(Collectors.toList()); <code>Naturalism
E
36

All of the answers on this topic that make use of the new Java 8 functions are neglecting to close the stream. The example in the accepted answer should be:

try (Stream<Path> filePathStream=Files.walk(Paths.get("/home/you/Desktop"))) {
    filePathStream.forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {
            System.out.println(filePath);
        }
    });
}

From the javadoc of the Files.walk method:

The returned stream encapsulates one or more DirectoryStreams. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

Eructate answered 3/12, 2015 at 17:27 Comment(3)
You should never iterate with Stream. You take a Stream reference, use it and through it away.Annmarie
@RudolfSchmidt you mean "throw it away"?Edentate
I mean the correct way is to use it in that way: Files.walk(Paths.get("/home/you/Desktop")).filter(Files::isRegularFile).forEach(filePath->...)Annmarie
G
35

One remark according to get all files in the directory.
The method Files.walk(path) will return all files by walking the file tree rooted at the given started file.

For instance, there is the next file tree:

\---folder
    |   file1.txt
    |   file2.txt
    |
    \---subfolder
            file3.txt
            file4.txt

Using the java.nio.file.Files.walk(Path):

Files.walk(Paths.get("folder"))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

Gives the following result:

folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt

To get all files only in the current directory use the java.nio.file.Files.list(Path):

Files.list(Paths.get("folder"))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

Result:

folder\file1.txt
folder\file2.txt
Gagliardi answered 30/1, 2019 at 12:24 Comment(5)
This should be the only answer left for the question right now in 2020 :)Sech
Upvote for the Files.list example. If you do not want to search recursively, this can be the best option sometimes.Bijou
java.nio.file.Files doesnt exist for me for some reasonArterio
AND, Files.list returns only files NOT foldersResht
what if i want to find, for example, amonst all the files, just the .pdf ones? how can I use the match function?Discursive
I
13

In Java 7 and higher you can use listdir

Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path file: stream) {
        System.out.println(file.getFileName());
    }
} catch (IOException | DirectoryIteratorException x) {
    // IOException can never be thrown by the iteration.
    // In this snippet, it can only be thrown by newDirectoryStream.
    System.err.println(x);
}

You can also create a filter that can then be passed into the newDirectoryStream method above

DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
    public boolean accept(Path file) throws IOException {
        try {
            return (Files.isRegularFile(path));
        } catch (IOException x) {
            // Failed to determine if it's a file.
            System.err.println(x);
            return false;
        }
    }
};

For other filtering examples, [see documentation].(http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob)

Instable answered 16/8, 2013 at 15:6 Comment(2)
I'm confused by the create filter example. What is newDirectoryStream.Filter<Path>. Can you show how that is declared?Alvita
I think i figured it out. its a copy and paste typo. there is a space between the "new" and the "DirectoryStream.Filter...". If i'm right recommend correcting your example.Alvita
P
12
import java.io.File;


public class ReadFilesFromFolder {
  public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
  static String temp = "";

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
    listFilesForFolder(folder);
  }

  public static void listFilesForFolder(final File folder) {

    for (final File fileEntry : folder.listFiles()) {
      if (fileEntry.isDirectory()) {
        // System.out.println("Reading files under the folder "+folder.getAbsolutePath());
        listFilesForFolder(fileEntry);
      } else {
        if (fileEntry.isFile()) {
          temp = fileEntry.getName();
          if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
            System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
        }

      }
    }
  }
}
Parr answered 23/11, 2012 at 15:43 Comment(1)
Welcome to Stack Overflow! Rather than only post a block of code, please explain why this code solves the problem posed. Without an explanation, this is not an answer.Horbal
B
10
private static final String ROOT_FILE_PATH="/";
File f=new File(ROOT_FILE_PATH);
File[] allSubFiles=f.listFiles();
for (File file : allSubFiles) {
    if(file.isDirectory())
    {
        System.out.println(file.getAbsolutePath()+" is directory");
        //Steps for directory
    }
    else
    {
        System.out.println(file.getAbsolutePath()+" is file");
        //steps for files
    }
}
Burglary answered 5/8, 2013 at 8:55 Comment(1)
This is the solution for android read all files and folders from sdcard or internal storage.Burglary
S
9

Just walk through all Files using Files.walkFileTree (Java 7)

Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        System.out.println("file: " + file);
        return FileVisitResult.CONTINUE;
    }
});
Stamin answered 22/5, 2014 at 18:6 Comment(1)
Note, that this code will throw an exception (and not report any further files) if for some file or directory the file attributes could not be read, e.g. because of permissions. Easy to reproduce on `C:`.Archive
A
5

If you want more options, you can use this function which aims to populate an arraylist of files present in a folder. Options are: recursivity and the pattern to match.

public static ArrayList<File> listFilesForFolder(final File folder,
        final boolean recursivity,
        final String patternFileFilter) {

    // Inputs
    boolean filteredFile = false;

    // Output
    final ArrayList<File> output = new ArrayList<File> ();

    // Foreach elements
    for (final File fileEntry : folder.listFiles()) {

        // If this element is a directory, do it recursively
        if (fileEntry.isDirectory()) {
            if (recursivity) {
                output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter));
            }
        }
        else {
            // If there isn't any pattern, the file is correct
            if (patternFileFilter.length() == 0) {
                filteredFile = true;
            }
            // Otherwise, we need to filter by pattern
            else {
                filteredFile = Pattern.matches(patternFileFilter, fileEntry.getName());
            }

            // If the file has a name which match with the pattern, then add it to the list
            if (filteredFile) {
                output.add(fileEntry);
            }
        }
    }

    return output;
}
Aidoneus answered 15/5, 2013 at 9:30 Comment(0)
I
4

A nice usage of java.io.FileFilter, as seen in Java - get the newest file in a directory?:

File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {          
    public boolean accept(File file) {
        return file.isFile();
    }
});
Illaudable answered 26/11, 2013 at 21:21 Comment(1)
docs.oracle.com/javase/7/docs/api/java/io/… public File[] listFiles() Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.Illaudable
R
3
File directory = new File("/user/folder");      
File[] myarray;  
myarray=new File[10];
myarray=directory.listFiles();
for (int j = 0; j < myarray.length; j++)
{
       File path=myarray[j];
       FileReader fr = new FileReader(path);
       BufferedReader br = new BufferedReader(fr);
       String s = "";
       while (br.ready()) {
          s += br.readLine() + "\n";
       }
}
Ryle answered 12/4, 2011 at 9:14 Comment(1)
You might want to add an explanation what you are trying to achieve, instead of only showing code. Furthermore, myarray=new File[10]; is not required, as it will be overwritten by the next line!Aaren
A
3

Simple example that works with Java 1.7 to recursively list files in directories specified on the command-line:

import java.io.File;

public class List {
    public static void main(String[] args) {
        for (String f : args) {
            listDir(f);
        }
    }

    private static void listDir(String dir) {
        File f = new File(dir);
        File[] list = f.listFiles();

        if (list == null) {
            return;
        }

        for (File entry : list) {
            System.out.println(entry.getName());
            if (entry.isDirectory()) {
                listDir(entry.getAbsolutePath());
            }
        }
    }
}
Argus answered 6/1, 2017 at 18:11 Comment(0)
F
3

While I do agree with Rich, Orian and the rest for using:

    final File keysFileFolder = new File(<path>); 
    File[] fileslist = keysFileFolder.listFiles();

    if(fileslist != null)
    {
        //Do your thing here...
    }

for some reason all the examples here uses absolute path (i.e. all the way from root, or, say, drive letter (C:\) for windows..)

I'd like to add that it is possible to use relative path as-well. So, if you're pwd (current directory/folder) is folder1 and you want to parse folder1/subfolder, you simply write (in the code above instead of ):

    final File keysFileFolder = new File("subfolder");
Filippa answered 19/5, 2017 at 8:23 Comment(0)
S
3

Java 8 Files.walk(..) is good when you are soore it will not throw Avoid Java 8 Files.walk(..) termination cause of ( java.nio.file.AccessDeniedException ) .

Here is a safe solution , not though so elegant as Java 8Files.walk(..) :

int[] count = {0};
try {
    Files.walkFileTree(Paths.get(dir.getPath()), new HashSet<FileVisitOption>(Arrays.asList(FileVisitOption.FOLLOW_LINKS)),
            Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException {
                    System.out.printf("Visiting file %s\n", file);
                    ++count[0];

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file , IOException e) throws IOException {
                    System.err.printf("Visiting failed for %s\n", file);

                    return FileVisitResult.SKIP_SUBTREE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir , BasicFileAttributes attrs) throws IOException {
                     System.out.printf("About to visit directory %s\n", dir);
                    return FileVisitResult.CONTINUE;
                }
            });
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Spendthrift answered 28/5, 2017 at 18:40 Comment(0)
J
2
    static File mainFolder = new File("Folder");
    public static void main(String[] args) {

        lf.getFiles(lf.mainFolder);
    }
    public void getFiles(File f) {
        File files[];
        if (f.isFile()) {
            String name=f.getName();

        } else {
            files = f.listFiles();
            for (int i = 0; i < files.length; i++) {
                getFiles(files[i]);
            }
        }
    }
Janik answered 23/12, 2013 at 7:5 Comment(0)
S
2

I think this is good way to read all the files in a folder and sub folder's

private static void addfiles (File input,ArrayList<File> files)
{
    if(input.isDirectory())
    {
        ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
        for(int i=0 ; i<path.size();++i)
        {
            if(path.get(i).isDirectory())
            {
                addfiles(path.get(i),files);
            }
            if(path.get(i).isFile())
            {
                files.add(path.get(i));
            }
        }
    }
    if(input.isFile())
    {
        files.add(input);
    }
}
Scion answered 24/2, 2015 at 16:13 Comment(0)
A
2
void getFiles(){
        String dirPath = "E:/folder_name";
        File dir = new File(dirPath);
        String[] files = dir.list();
        if (files.length == 0) {
            System.out.println("The directory is empty");
        } else {
            for (String aFile : files) {
                System.out.println(aFile);
            }
        }
    }
Amplifier answered 9/9, 2015 at 13:11 Comment(0)
T
2

Just to expand on the accepted answer I store the filenames to an ArrayList (instead of just dumping them to System.out.println) I created a helper class "MyFileUtils" so it could be imported by other projects:

class MyFileUtils {
    public static void loadFilesForFolder(final File folder, List<String> fileList){
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                loadFilesForFolder(fileEntry, fileList);
            } else {
                fileList.add( fileEntry.getParent() + File.separator + fileEntry.getName() );
            }
        }
    }
}

I added the full path to the file name. You would use it like this:

import MyFileUtils;

List<String> fileList = new ArrayList<String>();
final File folder = new File("/home/you/Desktop");
MyFileUtils.loadFilesForFolder(folder, fileList);

// Dump file list values
for (String fileName : fileList){
    System.out.println(fileName);
}

The ArrayList is passed by "value", but the value is used to point to the same ArrayList object living in the JVM Heap. In this way, each recursion call adds filenames to the same ArrayList (we are NOT creating a new ArrayList on each recursive call).

Thesis answered 19/7, 2017 at 22:3 Comment(0)
S
2

There are many good answers above, here's a different approach: In a maven project, everything you put in the resources folder is copied by default in the target/classes folder. To see what is available at runtime

 ClassLoader contextClassLoader = 
 Thread.currentThread().getContextClassLoader();
    URL resource = contextClassLoader.getResource("");
    File file = new File(resource.toURI());
    File[] files = file.listFiles();
    for (File f : files) {
        System.out.println(f.getName());
    }

Now to get the files from a specific folder, let's say you have a folder called 'res' in your resources folder, just replace:

URL resource = contextClassLoader.getResource("res");

If you want to have access in your com.companyName package then:

contextClassLoader.getResource("com.companyName");
Stetson answered 20/11, 2017 at 13:35 Comment(0)
M
2

A one liner using .map to get all the filenames in yourDirectory:

List<String> files = Files.list(Paths.get(yourDirectory)).map(path -> path.getFileName().toFile().getName()).collect(Collectors.toList());

Marathon answered 17/3, 2023 at 16:48 Comment(0)
C
2

Here's a short one for getting a list of files in a directory:

        File directory = new File("path");
        File[] files = directory.listFiles(File::isFile);
Curate answered 28/7, 2023 at 0:9 Comment(0)
A
1
package com;


import java.io.File;

/**
 *
 * @author ?Mukesh
 */
public class ListFiles {

     static File mainFolder = new File("D:\\Movies");

     public static void main(String[] args)
     {
         ListFiles lf = new ListFiles();
         lf.getFiles(lf.mainFolder);

         long fileSize = mainFolder.length();
             System.out.println("mainFolder size in bytes is: " + fileSize);
             System.out.println("File size in KB is : " + (double)fileSize/1024);
             System.out.println("File size in MB is :" + (double)fileSize/(1024*1024));
     }
     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]);
             }
         }
     }
}
Agamete answered 24/9, 2013 at 18:35 Comment(0)
O
1

You can put the file path to argument and create a list with all the filepaths and not put it the list manually. Then use a for loop and a reader. Example for txt files:

public static void main(String[] args) throws IOException{    
File[] files = new File(args[0].replace("\\", "\\\\")).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".txt"); } });
    ArrayList<String> filedir = new ArrayList<String>();
    String FILE_TEST = null;
    for (i=0; i<files.length; i++){
            filedir.add(files[i].toString());
            CSV_FILE_TEST=filedir.get(i) 

        try(Reader testreader = Files.newBufferedReader(Paths.get(FILE_TEST));
            ){
              //write your stuff
                 }}}
Octave answered 7/6, 2018 at 10:22 Comment(0)
T
1

We can use org.apache.commons.io.FileUtils, use listFiles() mehtod to read all the files in a given folder.

eg:

FileUtils.listFiles(directory, new String[] {"ext1", "ext2"}, true)

This read all the files in the given directory with given extensions, we can pass multiple extensions in the array and read recursively within the folder(true parameter).

Trope answered 2/12, 2020 at 14:58 Comment(0)
S
0

This will Read Specified file extension files in given path(looks sub folders also)

public static Map<String,List<File>> getFileNames(String 
dirName,Map<String,List<File>> filesContainer,final String fileExt){
    String dirPath = dirName;
    List<File>files = new ArrayList<>();
    Map<String,List<File>> completeFiles = filesContainer; 
    if(completeFiles == null) {
        completeFiles = new HashMap<>();
    }
    File file = new File(dirName);

    FileFilter fileFilter = new FileFilter() {
        @Override
        public boolean accept(File file) {
            boolean acceptFile = false;
            if(file.isDirectory()) {
                acceptFile = true;
            }else if (file.getName().toLowerCase().endsWith(fileExt))
              {
                acceptFile = true;
              }
            return acceptFile;
        }
    };
    for(File dirfile : file.listFiles(fileFilter)) {
        if(dirfile.isFile() && 
dirfile.getName().toLowerCase().endsWith(fileExt)) {
            files.add(dirfile);
        }else if(dirfile.isDirectory()) {
            if(!files.isEmpty()) {
                completeFiles.put(dirPath, files);  
            }

getFileNames(dirfile.getAbsolutePath(),completeFiles,fileExt);
        }
    }
    if(!files.isEmpty()) {
        completeFiles.put(dirPath, files);  
    }
    return completeFiles;
}
Statfarad answered 28/4, 2018 at 20:24 Comment(1)
Sorry if this a noob question but what should I pass as a files container ?Billionaire
V
0
package com.commandline.folder;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FolderReadingDemo {
    public static void main(String[] args) {
        String str = args[0];
        final File folder = new File(str);
//      listFilesForFolder(folder);
        listFilesForFolder(str);
    }

    public static void listFilesForFolder(String str) {
        try (Stream<Path> paths = Files.walk(Paths.get(str))) {
            paths.filter(Files::isRegularFile).forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void listFilesForFolder(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                System.out.println(fileEntry.getName());
            }
        }
    }

}
Vitale answered 21/9, 2018 at 8:57 Comment(0)
S
0
public static List<File> files(String dirname) {
    if (dirname == null) {
        return Collections.emptyList();
    }

    File dir = new File(dirname);
    if (!dir.exists()) {
        return Collections.emptyList();
    }

    if (!dir.isDirectory()) {
        return Collections.singletonList(file(dirname));
    }

    return Arrays.stream(Objects.requireNonNull(dir.listFiles()))
        .collect(Collectors.toList());
}
Sealskin answered 10/1, 2022 at 9:19 Comment(0)
P
-1

to prevent Nullpointerexceptions on the listFiles() function and recursivly get all files from subdirectories too..

 public void listFilesForFolder(final File folder,List<File> fileList) {
    File[] filesInFolder = folder.listFiles();
    if (filesInFolder != null) {
        for (final File fileEntry : filesInFolder) {
            if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry,fileList);
        } else {
            fileList.add(fileEntry);
        }
     }
    }
 }

 List<File> fileList = new List<File>();
 final File folder = new File("/home/you/Desktop");
 listFilesForFolder(folder);
Photogram answered 10/5, 2013 at 9:16 Comment(0)
J
-1
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AvoidNullExp {

public static void main(String[] args) {

    List<File> fileList =new ArrayList<>();
     final File folder = new File("g:/master");
     new AvoidNullExp().listFilesForFolder(folder, fileList);
}

    public void listFilesForFolder(final File folder,List<File> fileList) {
        File[] filesInFolder = folder.listFiles();
        if (filesInFolder != null) {
            for (final File fileEntry : filesInFolder) {
                if (fileEntry.isDirectory()) {
                    System.out.println("DIR : "+fileEntry.getName());
                listFilesForFolder(fileEntry,fileList);
            } else {
                System.out.println("FILE : "+fileEntry.getName());
                fileList.add(fileEntry);
            }
         }
        }
     }


}
Junoesque answered 31/12, 2013 at 23:5 Comment(0)
M
-1
/**
 * Function to read all mp3 files from sdcard and store the details in an
 * ArrayList
 */


public ArrayList<HashMap<String, String>> getPlayList() 
    {
        ArrayList<HashMap<String, String>> songsList=new ArrayList<>();
        File home = new File(MEDIA_PATH);

        if (home.listFiles(new FileExtensionFilter()).length > 0) {
            for (File file : home.listFiles(new FileExtensionFilter())) {
                HashMap<String, String> song = new HashMap<String, String>();
                song.put(
                        "songTitle",
                        file.getName().substring(0,
                                (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList
                songsList.add(song);
            }
        }
        // return songs list array
        return songsList;
    }

    /**
     * Class to filter files which have a .mp3 extension
     * */
    class FileExtensionFilter implements FilenameFilter 
    {
        @Override
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3") || name.endsWith(".MP3"));
        }
    }

You can filter any textfiles or any other extension ..just replace it with .MP3

Marnamarne answered 16/5, 2014 at 5:46 Comment(0)
G
-1

list down files from Test folder present inside class path

import java.io.File;
import java.io.IOException;

public class Hello {

    public static void main(final String[] args) throws IOException {

        System.out.println("List down all the files present on the server directory");
        File file1 = new File("/prog/FileTest/src/Test");
        File[] files = file1.listFiles();
        if (null != files) {
            for (int fileIntList = 0; fileIntList < files.length; fileIntList++) {
                String ss = files[fileIntList].toString();
                if (null != ss && ss.length() > 0) {
                    System.out.println("File: " + (fileIntList + 1) + " :" + ss.substring(ss.lastIndexOf("\\") + 1, ss.length()));
                }
            }
        }


    }


}
Grasp answered 4/11, 2014 at 13:25 Comment(0)
A
-1

This will work fine:

private static void addfiles(File inputValVal, ArrayList<File> files)
{
  if(inputVal.isDirectory())
  {
    ArrayList <File> path = new ArrayList<File>(Arrays.asList(inputVal.listFiles()));

    for(int i=0; i<path.size(); ++i)
    {
        if(path.get(i).isDirectory())
        {
            addfiles(path.get(i),files);
        }
        if(path.get(i).isFile())
        {
            files.add(path.get(i));
        }
     }

    /*  Optional : if you need to have the counts of all the folders and files you can create 2 global arrays 
        and store the results of the above 2 if loops inside these arrays */
   }

   if(inputVal.isFile())
   {
     files.add(inputVal);
   }

}
Alake answered 17/5, 2018 at 22:29 Comment(0)
D
-1

Given a baseDir, lists out all the files and directories below it, written iteratively.

    public static List<File> listLocalFilesAndDirsAllLevels(File baseDir) {

    List<File>  collectedFilesAndDirs   = new ArrayList<>();
    Deque<File> remainingDirs           = new ArrayDeque<>();

    if(baseDir.exists()) {
        remainingDirs.add(baseDir);

        while(!remainingDirs.isEmpty()) {
            File dir = remainingDirs.removeLast();
            List<File> filesInDir = Arrays.asList(dir.listFiles());
            for(File fileOrDir : filesInDir)  {
                collectedFilesAndDirs.add(fileOrDir);
                if(fileOrDir.isDirectory()) {
                    remainingDirs.add(fileOrDir);
                }
            }
        }
    }

    return collectedFilesAndDirs;
}
Desperado answered 8/1, 2019 at 21:15 Comment(0)
G
-4
import java.io.File;


public class Test {

public void test1() {
    System.out.println("TEST 1");
}

public static void main(String[] args) throws SecurityException, ClassNotFoundException{

    File actual = new File("src");
    File list[] = actual.listFiles();
    for(int i=0; i<list.length; i++){
        String substring = list[i].getName().substring(0, list[i].getName().indexOf("."));
        if(list[i].isFile() && list[i].getName().contains(".java")){
                if(Class.forName(substring).getMethods()[0].getName().contains("main")){
                    System.out.println("CLASS NAME "+Class.forName(substring).getName());
                }

         }
    }

}
}

Just pass your folder it will tell you main class about the method.

Gd answered 26/12, 2012 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.