I have this code here:
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>");
}
}
}
}
But I want to make it search on the folder C:\WorkFiles\ServletFiles
. How could I do this?
Update: When I tried to use private void ls(File f)
(without being static
), I got this error on the browser(running 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)