上传或下载时,首先要找到服务器程序所在的文件夹,
如果指定的文件夹不存在,则生成一个,
为了避免重复,要随即生成一个文件名。
- FacesContext context = FacesContext.getCurrentInstance();
- HttpServletRequest request = (HttpServletRequest) context
- .getExternalContext().getRequest();
- String filePath = request.getSession().getServletContext().getRealPath(
- "/")
- + "export//"; //获得程序所在目录下的export文件夹
- java.io.File upload = new java.io.File(request.getSession()
- .getServletContext().getRealPath("/")
- + "export");
- if (!upload.exists()) { //如果export文件夹不存在
- upload.mkdir(); //创建export文件夹
- }
- java.util.Calendar c = java.util.Calendar.getInstance();
- String newFileName = ""
- + c.get(Calendar.YEAR)
- + (("" + c.get(Calendar.MONTH)).length() == 1 ? "0"
- + (c.get(Calendar.MONTH) + 1)
- : (c.get(Calendar.MONTH) + 1))
- + (("" + c.get(Calendar.DATE)).length() == 1 ? ("0" + c
- .get(Calendar.DATE)) : (c.get(Calendar.DATE)))
- + (("" + c.get(Calendar.HOUR)).length() == 1 ? ("0" + c
- .get(Calendar.HOUR)) : (c.get(Calendar.HOUR)))
- + (("" + c.get(Calendar.MINUTE)).length() == 1 ? ("0" + c
- .get(Calendar.MINUTE)) : (c.get(Calendar.MINUTE)))
- + (("" + c.get(Calendar.SECOND)).length() == 1 ? ("0" + c
- .get(Calendar.SECOND)) : (c.get(Calendar.SECOND)))
- + "-" + c.get(Calendar.MILLISECOND) + ".xls"; //生成一个随即的文件名,避免重复,
- //这里生成的是.xls,你可以改成自己需要的文件类型
- String targetFile = filePath + newFileName; //完整的路径+文件名
targetFile就是完整文件路径名,然后用输出流输出即可。