Reputation: 61
I have wrote a piece of code for returning image whenever I hit the url with specific image name, and if image not found just return the error image.
@GET
@Path("/getImage/{param1}")
@Produces({ "image/png", "image/jpeg", "image/gif", "image/jpg" })
public Response getProductimage(@PathParam("param1") String recievedData) {
File file = null;
try {
file = new File("C:/Users/Gaurav/Desktop/AppData/"
+ recievedData);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
file = new File("C:/Users/Gaurav/Desktop/AppData/error.png");
System.out.println(e.getMessage());
}
return Response.ok(file).build();
}
Still I'm getting this error when trying to hit for wrong image
SEVERE: Servlet.service() for servlet [Jersey RESTful Application] in context with path [/WebServices] threw exception [org.glassfish.jersey.server.ContainerException: java.io.FileNotFoundException: C:\Users\Gaurav\Desktop\AppData\average11.png (The system cannot find the file specified)] with root cause
java.io.FileNotFoundException: C:\Users\Gaurav\Desktop\AppData\average.png15 (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:131)
at org.glassfish.jersey.message.internal.FileProvider.writeTo(FileProvider.java:115)
Whats wrong in the code?
Upvotes: 0
Views: 4242
Reputation: 523724
Calling new File("X:/non/existing/file")
will not throw any exception, so your catch
block will never be executed.
You should use .exists()
to check whether the file exists, or better, .canRead()
to check if you can really read it.
File file = new File("C:/Users/Gaurav/Desktop/AppData", recievedData);
if (!file.canRead()) {
file = new File("C:/Users/Gaurav/Desktop/AppData/error.png");
}
return Response.ok(file).build();
Upvotes: 3