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


当前回答

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

其他回答

在Java 8中,你可以这样做

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

它将打印文件夹中的所有文件,同时排除所有目录。如果你需要一个列表,下面的方法可以做到:

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

如果你想返回List<File>而不是List<Path>,只需映射它:

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

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

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);
            }
        }
    }
/**
 * 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模式。它确保在任何情况下流都将被关闭。