[英]How can I create a folder inside a server (Tomcat 7)?
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). 我正在使用java和jsf,我想在服务器内创建一个文件夹,然后临时保存文件并随后将其删除(而不是文件夹本身)。 I've tried this code:
我试过这段代码:
boolean folderPath;
folderPath = new File ("/Images").mkdir();
but the code above created the folder in my local disk. 但是上面的代码在我的本地磁盘中创建了该文件夹。
Don't do that. 不要那样做。 You can never guarantee that the WAR folder is writable or even on physical disk.
您永远不能保证WAR文件夹是可写的,甚至不能在物理磁盘上。 For example, when the servletcontainer is configured to expand the WAR into memory instead of into disk.
例如,当servlet容器配置为将WAR扩展到内存而不是磁盘中时。
As it's apparently a temporary file, rather just use File#createTempFile()
: 因为它显然是一个临时文件,所以只需使用
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. 或者使用固定磁盘文件系统上的外部文件夹,其绝对路径将设置为VM参数或某些配置设置。
Update : you could use a servlet to display that file. 更新 :您可以使用servlet来显示该文件。 I gather that it's an image file.
我收集到它是一个图像文件。 You can use
<h:graphicImage>
wherein you set the temp file's filename in the path. 您可以使用
<h:graphicImage>
其中在路径中设置临时文件的文件名。
Eg inside the bean: 例如,在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): 然后应该在
/images/*
上侦听的servlet如下所示(在练习中省略了例外检查):
@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.
}
}
With Primefaces, I use this: 对于Primefaces,我使用以下命令:
Import this : 导入此:
import javax.faces.context.ExternalContext;
导入javax.faces.context.ExternalContext;
Then the main class: 然后是主类:
String resultFolder = "newFolder";
字符串resultFolder =“ newFolder”;
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
ExternalContext extContext = FacesContext.getCurrentInstance()。getExternalContext();
File result = new File(extContext.getRealPath("//WEB-INF//" + resultFolder ).mkdir();
文件结果=新文件(extContext.getRealPath(“ // WEB-INF //” + resultFolder).mkdir();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.