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..
source to share
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
.
source to share
<%=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
source to share