I am struggling with getting a relative path to the fileroot directory that I have placed in the web root folder. I am trying to access this directory from a class to return the names of files in it via a Web Service. The folder contains images and XML files.
Here is my project structure as seen from exploded .WAR file -
MyProject
- fileroot
- css
- ...
- WEB-INF
|--classes
I am able to get this to work when I use a hard-coded absolute path on my local drive to read files on the directory. However, I need this to work on the web server where absolute path's are not possible.
I need to access this folder from within my class to be able to apply some processing on the XML while being able to serve images from the folder for webpages.
Here is the code written for reading the directory -
package com.xyz.executor;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
/**
*
* @author AJ
*/
public class GetDirectories {
public String basePath = "/fileroot";
public String directoryName;
public GetDirectories() {
}
public GetDirectories(String DirectoryName) {
this.directoryName = DirectoryName;
basePath = basePath + "/" + directoryName;
}
public ArrayList<String> read() {
ArrayList<String> DirectoryList = new ArrayList<>();
try {
File f = new File(basePath); // current directory
FileFilter directoryFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
File[] files = f.listFiles(directoryFilter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
DirectoryList.add(file.getName());
} else {
System.out.print(" file:");
}
System.out.println(file.getName());
}
} catch (Exception e) {
System.out.println("Exception occurred (GetDirectories) : " + e.toString());
e.printStackTrace();
System.out.println("**************************");
}
return DirectoryList;
}
}
I get a null pointer exception as f.listFiles(directoryFilter) returns null because of which I suspect there is an issue with the path.
Question 1, How can I get the application root path within a class file?
Question 2, Am I doing the right thing by placing the directory within the application root? Or should I place this in another location on the drive?
P.S: I wrote a web application earlier which read a .properties file stored in the classpath similar to this question. However, this does not seem like a good idea for bulk number of files
Servlet, and pass this information to your class as a parameter. I.e. it is not accessible from within a POJO.Servlet, moved myfilerootdirectory toWEB-INFand then usedServletContextto get access to the file. I will edit my question and add the code.