获取当前目录下的文件和目录方法一般分为两步:
- 获取当前目录的绝对路径。
- 遍历当前目录,获取其中所有的文件和目录。
具体的步骤如下:
1. 获取当前目录的绝对路径
在 JSP 中,可以通过 pageContext
对象的 getServletContext()
方法获取 ServletContext
对象,然后通过 getRealPath()
方法获取当前应用程序的根目录的绝对路径,再加上相对路径就可以得到当前目录的绝对路径。
<%
String relativePath = ".";
String absolutePath = getServletContext().getRealPath(relativePath);
out.print(absolutePath);
%>
上面的示例中,relativePath
参数指定为 "."
,表示当前目录,getRealPath()
方法返回的是服务器文件系统中的路径,所以得到的是当前目录在服务器文件系统中的绝对路径,这个路径可能跟客户端本地的路径不一样。
2. 遍历当前目录,获取其中所有的文件和目录
Java 提供了 File
类用于操作文件系统中的文件和目录,具体的步骤如下:
<%
String relativePath = ".";
String absolutePath = getServletContext().getRealPath(relativePath);
File currentDir = new File(absolutePath);
File[] files = currentDir.listFiles();
for (File file : files) {
if (file.isFile()) {
out.print("File: " + file.getName() + "<br>");
} else if (file.isDirectory()) {
out.print("Directory: " + file.getName() + "<br>");
}
}
%>
上面的示例中,listFiles()
方法返回的是当前目录中的所有文件和目录的 File
对象数组,我们可以通过 for
循环遍历这个数组,并使用 isFile()
和 isDirectory()
方法判断每个元素是文件还是目录。
下面是完整的 JSP 代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Get files and directories in current directory</title>
</head>
<body>
<%
String relativePath = ".";
String absolutePath = getServletContext().getRealPath(relativePath);
File currentDir = new File(absolutePath);
File[] files = currentDir.listFiles();
for (File file : files) {
if (file.isFile()) {
out.print("File: " + file.getName() + "<br>");
} else if (file.isDirectory()) {
out.print("Directory: " + file.getName() + "<br>");
}
}
%>
</body>
</html>
示例说明:
假设当前目录下有以下文件和目录:
- documents/
- index.html
- style.css
运行上面的 JSP 代码,会输出如下内容:
Directory: documents
File: index.html
File: style.css
另外一个示例:
假设我们需要获取 D 盘根目录下的所有文件和目录,可以将 relativePath
参数设为 /D:/
,代码如下:
<%
String relativePath = "/D:/";
String absolutePath = getServletContext().getRealPath(relativePath);
File currentDir = new File(absolutePath);
File[] files = currentDir.listFiles();
for (File file : files) {
if (file.isFile()) {
out.print("File: " + file.getName() + "<br>");
} else if (file.isDirectory()) {
out.print("Directory: " + file.getName() + "<br>");
}
}
%>
运行以上代码,会输出 D 盘根目录下的所有文件和目录。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:jsp编程获取当前目录下的文件和目录及windows盘符的方法 - Python技术站