我有一个主页,其中有一个下载目录。 我想从其目录中自动读取该主页的所有文件。
例如,我有主页:www.homepage.org
和子目录 resources/downloads
,其中包含我想要显示的下载文件。
我有一个运行 Spring 和 JSP 的 Java 服务器,并尝试了以下方法,但根本不起作用:
String path = request.getContextPath();
path += DOWNLOADS;
URL url = null;
String server = request.getServerName();
try {
url = new URL("https", server, request.getLocalPort(), path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url != null) {
String externalForm = url.toExternalForm();
File directory = new File(externalForm);
String[] files = directory.list();
for (String file : files) {
;
}
}
最佳答案
您可以使用 Servlet。如果您的资源目录位于 Web 应用程序的根目录中,则使用
PrintWriter writer = response.getWriter();
String path = getServletContext().getRealPath("/resources/downloads");
File directory = new File(path);
if(directory.isDirectory()){
String[] files = directory.list();
for (String file : files) {
writer.write(file + "<br/>");
}
} else writer.write(directory.getAbsolutePath() + "could not be found");
关于java - 获取网络中某个目录的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13628301/