Reputation: 2304
I'm new to Java EE, and I want to display in a webpage a list of PDF thumbnails. These PDF are stored in a folder in src/main/webapp/pdf
, and I want to read this folder to get all the filenames. Here is my code :
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) {
try {
res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");
PrintWriter out = res.getWriter();
File pdfFolder = new File("/pdf");
for (File pdf : pdfFolder.listFiles()) { // Line 27
out.println(pdf.getName());
}
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
}
}
When I run this code, I get a NullPointerException
:
java.lang.NullPointerException
com.multi.services.ListFiles.doGet(ListFiles.java:27)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Here is my structure :
What I want to have is a web service that reads the PDF folder and returns a JSON containing the PDF filenames, and I will call this service in a JavaScript using Ajax.
Can anyone help me to make my script running well ? Or has anyone a better solution ?
Thanks :)
Upvotes: 2
Views: 5785
Reputation: 1
Berilium, I've tried your suggestion and it works fine !
In order to clarify this item, I show my case:
try {
File pdfFolder=new File(request.getSession().getServletContext().getRealPath("img/fotos"));
System.out.println("PATH---->"+pdfFolder);
for (File pdf : pdfFolder.listFiles()) {
String s = pdf.getName();
String t = s.substring(0, s.lastIndexOf("."));
if (t.equals(nombre)) {
Foto = s;
break;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 12998
A quote from the Javadoc of File.listFiles()
returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
So your path is not correct (as the current directory of your servlet container is undefined). You have these possibilities here:
Use the absolute path (this is appropriate, if you store the PDF outside of your webapp)
Use getRealPath()
(this should be suitable for your use case; PDFs are part of webapp):
File pdfFolder =
new File(req.getSession().getServletContext().getRealPath("/pdf"));
Upvotes: 4