List server directory contents using JSP

I have files on the server in the following directory:

D:\tomcat8\webapps\schema_files\

      

I want to list all the files found in the above directory.

What i tried

<%
String folder=application.getRealPath("D:/tomcat8/webapps/schema_files");
File file=new File(folder);
String fileNames[]=file.list();
System.out.println("fileNames[] : "+fileNames[0]);
%>

      

Does not work.

However, if I store the files in the application itself in the "/ WEB-INF / filefolder" then the following code works.

   <%
  String folder=application.getRealPath("/WEB-INF/filefolder");
  File file=new File(folder);
  String fileNames[]=file.list();
  System.out.println("fileNames[] : "+fileNames[0]);
  %>

      

Please help me..

+3


source to share


3 answers


You can use application.getRealPath(String args0)

and application.getContextPath()

by pointing to your server directory like this:

File file=new  File(application.getRealPath(application.getContextPath())); 
String fileNames[]=file.list();
for(int i=0;i<fileNames.length;i++)
    System.out.println(fileNames[i]);

      



application

- an implicit object available to JSP, in the same way as session

, and request

.

+1


source


This works, but there might be a better approach explicitly for JSP



<%
 File file=new File("D:\\tomcat8\\webapps\\schema_files");
 String fileNames[]=file.list();
 System.out.println("fileNames[] : "+fileNames[0]);
%>

      

0


source


<%=request.getContextPath()%>

can get the root path of your application, so it looks like localhost:port/yourappname

. Then all you have to do is assign this to another variable like string path and add your folder path or something.

Example:

<%=request.getContextPath()%>/folder1/folder2/webpage.html 

      

0


source







All Articles