Recursively list files in Java

后端 未结 27 1620
走了就别回头了
走了就别回头了 2020-11-22 00:29

How do I recursively list all files under a directory in Java? Does the framework provide any utility?

I saw a lot of hacky implementations. But none from the fra

27条回答
  •  遇见更好的自我
    2020-11-22 00:55

    // Ready to run

    import java.io.File;
    
    public class Filewalker {
    
        public void walk( String path ) {
    
            File root = new File( path );
            File[] list = root.listFiles();
    
            if (list == null) return;
    
            for ( File f : list ) {
                if ( f.isDirectory() ) {
                    walk( f.getAbsolutePath() );
                    System.out.println( "Dir:" + f.getAbsoluteFile() );
                }
                else {
                    System.out.println( "File:" + f.getAbsoluteFile() );
                }
            }
        }
    
        public static void main(String[] args) {
            Filewalker fw = new Filewalker();
            fw.walk("c:\\" );
        }
    
    }
    

提交回复
热议问题