Pradip Shenolkar
Pradip Shenolkar

Reputation: 817

list contents of a server directory using JSP

I have files on server in following directory:

D:\tomcat8\webapps\schema_files\

I want to list all files present in above directory.

What I have 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]);
%>

Its not working.

However if I store files in application itself at "/WEB-INF/filefolder" then 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..

Upvotes: 3

Views: 3151

Answers (3)

Dashovsky
Dashovsky

Reputation: 137

<%=request.getContextPath()%> can get you root path of your application so it's gonna be something like localhost:port/yourappname. Then all you need to do it's assign this to some other variable like string path and add your subfolder path or something.

Example:

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

Upvotes: 0

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

You can use application.getRealPath(String args0) and application.getContextPath() 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 is an implicit object available in JSP, just like session and request.

Upvotes: 1

Pradip Shenolkar
Pradip Shenolkar

Reputation: 817

This is working, but there might be better approach which is explicit for JSP

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

Upvotes: 0

Related Questions