How do I iterate through the files in a directory in Java?

前端 未结 10 2327
星月不相逢
星月不相逢 2020-11-22 08:37

I need to get a list of all the files in a directory, including files in all the sub-directories. What is the standard way to accomplish directory iteration with Java?

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 09:19

    You can also misuse File.list(FilenameFilter) (and variants) for file traversal. Short code and works in early java versions, e.g:

    // list files in dir
    new File(dir).list(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            String file = dir.getAbsolutePath() + File.separator + name;
            System.out.println(file);
            return false;
        }
    });
    

提交回复
热议问题