• Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing directories using a JSP

 
Tony Walters
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to get a directory list using a JSP. The directory (called 'xml')is directly beneath the webapps directory (in Tomcat 5). For some reason the code works when not in a JSP. Put it into a JSP and it doesn't. Here's the code:
<%
java.util.ArrayList lessons = new java.util.ArrayList();
try {
java.io.File file = new java.io.File("xml");
String [] files = file.listFiles();
for(int i=0; i<files.length; i++) {
out.println(files[i] + "<br>");
if(files[i].startsWith("jav") && files[i].endsWith(".xml")) {
lessons.add("xml/" + files[i]);
}
}
} catch(Exception ignore) {
out.println("Error: " + ignore);
}
request.setAttribute("lessons", lessons);
%>
The list() method doesn't seem to return anything (resulting in a NullPointerException when I try and access it). Any clues?
Ta!
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65522
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code makes the erroneous assumption that the 'current working directory' for the JSP is the webapps folder.
Check out the getRealPath() method of ServletContext for a way to map relative paths to real ones.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65522
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
P.S. UBB code tags are our friends! Please use them whenever posting code fragments.
 
Tony Walters
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for that. Now works fine.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!