ksa
ksa

Reputation: 331

browsing files and folders using jsp

i want to display directory and its files in link format that is if i click the directory it should display the files in that directory.i tried to get the directory as a link but dont know how to get the files

my code for getting directory as a link.

<%
try{
File dirName = new File("/home/adapco/Desktop/Startest/");

if (dirName.exists()&& dirName.isDirectory())
{
//out.print("path: " + dirName.getAbsolutePath() + "<br>");
String[] allFiles = dirName.list();
for (int i=0; i < allFiles.length; i++)
{
out.println(allFiles[i] + "<br>");
%>
<a href="Startest/<%=allFiles[i]%>"><%=allFiles[i]%></a>
}
}
}
catch (IOException ex){
out.println("Exception Occured");
}
%>

i tried to get the file in the same manner but it isnt working

File folder = new File("/home/adapco/Desktop/Startest/");
File[] listOfFiles = folder.listFiles();

i want to know how to get both directory and files and link them up in order to browse.

Upvotes: 1

Views: 4108

Answers (1)

alexey28
alexey28

Reputation: 5220

Result of folder.listFiles() is array of files and directories. It is all there. You can use file.isDirectory() or file.isFile() to detect is it directory or file.

You will have servlet/controller that is mapped to "/filesystem/*", that you can extract path that is after filesystem/folder1/folder2 -> folder1/folder2. Add to this path you filesystem, create file and return content of folder. So link to folder2 will be:

<a href="<c:url value='/filesystem/folder1/folder2'/>">folder2</a>

To encode not supported in url symbols use URLEncoder() for folders names.

Upvotes: 1

Related Questions