JSP uses Javabean to get all files of the specified drive letter - it can be used to search for web music players

Description: JSP uses Javabean to get all files of the specified drive letter - it can be used to search for web music players

Principle: Use the listFiles of the File object in JavaBean to get the file array, and then judge whether it is a directory, if it is, use the recursive principle to repeat it continuously, otherwise if it is a file, save it directly, save it in the List, and then get it in the JSP file after the acquisition is complete the List object, then use the iterator for output

Tip: If the number of files is large, it may take a while to display

Code: JavaBean code

package bean;

import java.util. *;
import java.io. *;

public class JavaBean{
    private List<String> all = new ArrayList<>(); // absolute path to save all files
    public void getFile(File file) { // get all files
        
        if (file != null) { // Check if the given file is empty
        	
            if (file.isDirectory()) { // Determine if it is a directory
                File[] list = file.listFiles(); // if yes, list all directories

                if (list != null) { // Determine if it is an empty directory
                	for (int i = 0; i < list.length; i++) {
                        getFile(list[i]); // recurse if not
                    }
                }
            }
            else{
                all.add(file.getAbsolutePath()); // otherwise get the absolute path if it is a file
            }
        }
    }

    /* Get the linked list of saved file paths */
    public List<String> getList() {
        return this.all;
    }
}

    Code: JSP code

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>

<%-- import package--%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="bean.JavaBean"%>

<!DOCTYPE html>
<html>
<head>
	<title>jsp</title>
	<meta charset="UTF-8" />
<body>
	<%
		/* List all file information of the specified drive letter in the form of absolute path */
		JavaBean bean = new JavaBean(); // instantiate the object
		File file = new File("F:" + File.separator); // instantiate the file object
		bean.getFile(file); // get all files

		List<String> list = bean.getList(); // return a list of file paths
		Iterator<String> iter = list.iterator(); // get the iterator

		while (iter.hasNext()) { // Take it out in turn
	%>
			<%-- use expression for output--%>
			<%=iter.next()%><br>
	<%
		}
	%>
</body>
</html>

operation result:


File organization: The compiled .class file of java must be placed in the classes folder under WEB-INF



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325604455&siteId=291194637