Reputation: 55
Im using java and jsf and I would like to create a folder within the server and then temporary save the files and delete it afterwards(not the folder itself). I've tried this code:
boolean folderPath;
folderPath = new File ("/Images").mkdir();
but the code above created the folder in my local disk.
Upvotes: 1
Views: 3179
Reputation: 78
With Primefaces, I use this:
Import this :
import javax.faces.context.ExternalContext;
Then the main class:
String resultFolder = "newFolder";
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
File result = new File(extContext.getRealPath("//WEB-INF//" + resultFolder ).mkdir();
Upvotes: 0
Reputation: 1108722
Don't do that. You can never guarantee that the WAR folder is writable or even on physical disk. For example, when the servletcontainer is configured to expand the WAR into memory instead of into disk.
As it's apparently a temporary file, rather just use File#createTempFile()
:
File tempFile = File.createTempFile("filename", ".png");
// ...
Or use an external folder on the fixed disk file system whose absolute path is to be set as VM argument or some configuration setting.
Update: you could use a servlet to display that file. I gather that it's an image file. You can use <h:graphicImage>
wherein you set the temp file's filename in the path.
E.g. inside the bean:
this.filename = tempFile.getName();
and then in the view:
<h:graphicImage value="images/#{bean.filename}" />
The servlet which should listen on /images/*
can then just look like as follows (exceptional checks are omitted for your exercise):
@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File file = new File(System.getProperty("java.io.tmpdir"), request.getPathInfo());
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", String.valueOf(file.length()));
InputStream input = new FileInputStream(file);
OutputStream output = response.getOutputStream();
// Now write input to output the usual way.
}
}
Upvotes: 2