如何通过Java读取文件夹中的所有文件?这与哪个API无关。


当前回答

一个注释根据获得目录中的所有文件。 方法files .walk(path)将通过遍历以给定起始文件为根的文件树来返回所有文件。

例如,下面有一个文件树:

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

使用java.nio.file.Files.walk(路径):

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

给出如下结果:

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

要获取当前目录下的所有文件,请使用java.nio.file.Files.list(Path):

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

结果:

folder\file1.txt
folder\file2.txt

其他回答

/**
 * 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"));
        }
    }

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

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

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

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

这个例子使用了API指南中推荐的try-with-resources模式。它确保在任何情况下流都将被关闭。

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

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

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

出于某种原因,这里所有的例子都使用绝对路径(即从根目录开始,或者,对于windows..)

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

    final File keysFileFolder = new File("subfolder");
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";
       }
}
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);
            }
        }
    }