gpt4 book ai didi

java - 将根文件夹设置为索引

转载 作者:行者123 更新时间:2023-12-02 00:50:53 26 4
gpt4 key购买 nike

我这里有这段代码:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
*
* @author Nathan Campos
*/
public class Files extends HttpServlet {
PrintWriter out = null; // moved outside doGet() for use in ls()
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
// PrintWriter out = response.getWriter(); would create a copy no accessable in ls()
out = response.getWriter(); // this uses the out declared outside
File startDir = new File("C:\\test");
ls(startDir);
}

private void ls(File f) {
File[] list = f.listFiles();
if ( list == null ) {
out.println("Returned null");
return; // otherwise the for loop will crash
}
for(File file : list) {
if(file.isDirectory()) {
ls(file);
} else {
out.println("<a href='+file.toURL()+'>'+file.getName()+'</a>");
}
}
}
}

但我想让它在文件夹 C:\WorkFiles\ServletFiles 上搜索。我怎样才能做到这一点?

更新:当我尝试使用private void ls(File f)(没有static)时,我在浏览器(运行 Tomcat):

java.lang.NullPointerException    Files.ls(Files.java:30)    Files.doGet(Files.java:18)    javax.servlet.http.HttpServlet.service(HttpServlet.java:627)    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

最佳答案

应从配置中读取您启动的目录。不过你也可以这样调用它:

PrintWriter out = null; // moved outside doGet() for use in ls()

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
out = response.getWriter();

File startDir = new File("C:\\WorkFiles\\ServletFiles");
ls( startDir );
}

ls() 中的打印行有问题(不能混合 ' 和 "),应重写为

out.println("<a href="+file.toURL()+'>'+file.getName()+"</a>");

(假设您不希望在重新渲染的 html 页面中输出而不是标准输出)

注意:已弃用的 file.toURL() 方法会抛出 MalformedURLException

编辑:

由于 listFiles 可能返回 null,因此您还应该添加

File[] list = f.listFiles();
if ( list == null ) return;

关于java - 将根文件夹设置为索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3205664/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com