如何从Java中读取文件夹中的所有文件?

时间:2022-03-01 06:16:47

How to read all the files in a folder through Java?

如何通过Java读取文件夹中的所有文件?

25 个解决方案

#1


733  

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);

Files.walk API is available from Java 8.

文件。可以从Java 8中获得walk API。

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

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

这个例子使用了API指南中推荐的试用资源模式。它确保了无论在什么情况下,流都将被关闭。

#2


117  

File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();

for (File file : listOfFiles) {
    if (file.isFile()) {
        System.out.println(file.getName());
    }
}

#3


79  

In Java 8 you can do this

在Java 8中,你可以这样做。

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 而不是List ,只需映射它:

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.

您还需要确保关闭流!否则,您可能会遇到一个异常,告诉您有太多的文件是打开的。在这里阅读更多信息。

#4


16  

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:

在这个主题中,使用新的Java 8函数的所有答案都忽略了关闭流。被接受的答案应该是:

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:

从文件的javadoc。走路的方法:

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.

返回的流封装了一个或多个DirectoryStreams。如果需要及时处理文件系统资源,则应该使用try- resources构造来确保流操作完成后调用流的close方法。

#5


8  

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());
        }

      }
    }
  }
}

#6


7  

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
    }
}

#7


4  

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

只需遍历所有使用文件的文件。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;
    }
});

#8


4  

In Java 7 you can now do it this way - http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#listdir

在Java 7中,现在可以这样做——http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#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

您还可以创建一个过滤器,然后将其传递到上面的newDirectoryStream方法。

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;
        }
    }
};

Other filtering examples - http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob

其他过滤例子:http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob。

#9


3  

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

如果您想要更多的选项,您可以使用这个函数来填充文件夹中当前文件的arraylist。选项是:递归和模式匹配。

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

    // Inputs
    boolean filteredFile = false;

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

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

        // If this element is a directory, do it recursivly
        if (fileEntry.isDirectory()) {
            if (recursivity) {
                output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter));
            }
        }
        else {
            // If there is no 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;
}

Best, Adrien

最好,阿德里安

#10


2  

nice usage of java.io.FileFilter as seen on https://*.com/a/286001/146745

好使用io。如在https://*.com/a/286001/146745上看到的FileFilter。

File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {          
    public boolean accept(File file) {
        return file.isFile();
    }
});

#11


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]);
            }
        }
    }

#12


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);
    }
}

#13


2  

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

与Java 1.7一起工作的简单示例,递归地列出命令行中指定的目录中的文件:

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());
            }
        }
    }
}

#14


1  

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";
       }
}

#15


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]);
             }
         }
     }
}

#16


1  

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

虽然我同意Rich, Orian和其他的使用:

    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..)

由于某些原因,这里的所有示例都使用绝对路径(即从根到windows的所有方法,或者说是驱动器号(C:\))。

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 ):

我想补充的是,可以使用相对路径。因此,如果您是pwd(当前目录/文件夹)是folder1,您想要解析folder1/子文件夹,您只需编写(在上面的代码中而不是):

    final File keysFileFolder = new File("subfolder");

#17


0  

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);
            }
         }
        }
     }


}

#18


0  

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()));
                }
            }
        }


    }


}

#19


0  

/**
 * 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

您可以过滤任何文本文件或任何其他扩展。把它换成。mp3。

#20


0  

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);
            }
        }
    }

#21


0  

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 ) .

Java 8 .walk(..)当你是soore的时候,它是好的,它不会抛弃Java 8 .walk(..)终止原因(Java .nio.file)。AccessDeniedException)。

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

这里有一个安全的解决方案,虽然没有Java 8 .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();
}

#22


0  

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:

为了扩展所接受的答案,我将文件名存储到一个ArrayList(而不是将它们转储到System.out.println)中,我创建了一个助手类“MyFileUtils”,以便其他项目可以导入它:

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).

ArrayList通过“value”传递,但该值用于指向位于JVM堆中的相同ArrayList对象。这样,每个递归调用都会将文件名添加到相同的ArrayList中(我们不会在每次递归调用上创建一个新的ArrayList)。

#23


0  

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

上面有许多很好的答案,这里有一个不同的方法:在maven项目中,您放入资源文件夹中的所有内容都将在target/classes文件夹中默认复制。查看运行时可用的内容。

 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:

现在,要从一个特定的文件夹中获取文件,假设您的资源文件夹中有一个名为“res”的文件夹,只需替换:

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

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

如果您想在您的com.companyName包中访问:

contextClassLoader.getResource("com.companyName");

#24


-1  

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

要防止listFiles()函数中的nullpointerexception,也要从子目录中获取所有的文件。

 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);

#25


-2  

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.

只要通过你的文件夹,它就会告诉你主要的方法。

#1


733  

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);

Files.walk API is available from Java 8.

文件。可以从Java 8中获得walk API。

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

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

这个例子使用了API指南中推荐的试用资源模式。它确保了无论在什么情况下,流都将被关闭。

#2


117  

File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();

for (File file : listOfFiles) {
    if (file.isFile()) {
        System.out.println(file.getName());
    }
}

#3


79  

In Java 8 you can do this

在Java 8中,你可以这样做。

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 而不是List ,只需映射它:

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.

您还需要确保关闭流!否则,您可能会遇到一个异常,告诉您有太多的文件是打开的。在这里阅读更多信息。

#4


16  

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:

在这个主题中,使用新的Java 8函数的所有答案都忽略了关闭流。被接受的答案应该是:

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:

从文件的javadoc。走路的方法:

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.

返回的流封装了一个或多个DirectoryStreams。如果需要及时处理文件系统资源,则应该使用try- resources构造来确保流操作完成后调用流的close方法。

#5


8  

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());
        }

      }
    }
  }
}

#6


7  

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
    }
}

#7


4  

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

只需遍历所有使用文件的文件。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;
    }
});

#8


4  

In Java 7 you can now do it this way - http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#listdir

在Java 7中,现在可以这样做——http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#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

您还可以创建一个过滤器,然后将其传递到上面的newDirectoryStream方法。

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;
        }
    }
};

Other filtering examples - http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob

其他过滤例子:http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob。

#9


3  

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

如果您想要更多的选项,您可以使用这个函数来填充文件夹中当前文件的arraylist。选项是:递归和模式匹配。

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

    // Inputs
    boolean filteredFile = false;

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

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

        // If this element is a directory, do it recursivly
        if (fileEntry.isDirectory()) {
            if (recursivity) {
                output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter));
            }
        }
        else {
            // If there is no 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;
}

Best, Adrien

最好,阿德里安

#10


2  

nice usage of java.io.FileFilter as seen on https://*.com/a/286001/146745

好使用io。如在https://*.com/a/286001/146745上看到的FileFilter。

File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {          
    public boolean accept(File file) {
        return file.isFile();
    }
});

#11


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]);
            }
        }
    }

#12


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);
    }
}

#13


2  

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

与Java 1.7一起工作的简单示例,递归地列出命令行中指定的目录中的文件:

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());
            }
        }
    }
}

#14


1  

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";
       }
}

#15


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]);
             }
         }
     }
}

#16


1  

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

虽然我同意Rich, Orian和其他的使用:

    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..)

由于某些原因,这里的所有示例都使用绝对路径(即从根到windows的所有方法,或者说是驱动器号(C:\))。

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 ):

我想补充的是,可以使用相对路径。因此,如果您是pwd(当前目录/文件夹)是folder1,您想要解析folder1/子文件夹,您只需编写(在上面的代码中而不是):

    final File keysFileFolder = new File("subfolder");

#17


0  

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);
            }
         }
        }
     }


}

#18


0  

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()));
                }
            }
        }


    }


}

#19


0  

/**
 * 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

您可以过滤任何文本文件或任何其他扩展。把它换成。mp3。

#20


0  

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);
            }
        }
    }

#21


0  

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 ) .

Java 8 .walk(..)当你是soore的时候,它是好的,它不会抛弃Java 8 .walk(..)终止原因(Java .nio.file)。AccessDeniedException)。

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

这里有一个安全的解决方案,虽然没有Java 8 .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();
}

#22


0  

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:

为了扩展所接受的答案,我将文件名存储到一个ArrayList(而不是将它们转储到System.out.println)中,我创建了一个助手类“MyFileUtils”,以便其他项目可以导入它:

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).

ArrayList通过“value”传递,但该值用于指向位于JVM堆中的相同ArrayList对象。这样,每个递归调用都会将文件名添加到相同的ArrayList中(我们不会在每次递归调用上创建一个新的ArrayList)。

#23


0  

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

上面有许多很好的答案,这里有一个不同的方法:在maven项目中,您放入资源文件夹中的所有内容都将在target/classes文件夹中默认复制。查看运行时可用的内容。

 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:

现在,要从一个特定的文件夹中获取文件,假设您的资源文件夹中有一个名为“res”的文件夹,只需替换:

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

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

如果您想在您的com.companyName包中访问:

contextClassLoader.getResource("com.companyName");

#24


-1  

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

要防止listFiles()函数中的nullpointerexception,也要从子目录中获取所有的文件。

 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);

#25


-2  

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.

只要通过你的文件夹,它就会告诉你主要的方法。