Recursively list files in Java

后端 未结 27 2284
走了就别回头了
走了就别回头了 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:41

    Based on stacker answer. Here is a solution working in JSP without any external libraries so you can put it almost anywhere on your server:

    
    <%@ page session="false" %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.io.*" %>
    <%@ page contentType="text/html; charset=UTF-8" %>
    
    <%!
        public List files = new ArrayList();
        /**
            Fills files array with all sub-files.
        */
        public void walk( File root ) {
            File[] list = root.listFiles();
    
            if (list == null) return;
    
            for ( File f : list ) {
                if ( f.isDirectory() ) {
                    walk( f );
                }
                else {
                    files.add(f.getAbsolutePath());
                }
            }
        }
    %>
    <%
        files.clear();
        File jsp = new File(request.getRealPath(request.getServletPath()));
        File dir = jsp.getParentFile();
        walk(dir);
        String prefixPath = dir.getAbsolutePath() + "/";
    %>
    

    Then you just do something like:

        
      <% for (String file : files) { %> <% if (file.matches(".+\\.(apk|ipa|mobileprovision)")) { %>
    • <%=file.replace(prefixPath, "")%>
    • <% } %> <% } %>

提交回复
热议问题