无法在Java中创建缓存文件

时间:2017-05-06 13:25:40

标签: java servlets caching image-uploading

我在网站上传图片时遇到问题。有时,它上传。但有时它也会说can’t create cache file。我该如何解决?

这是我的代码:

    File file = new File(imagePath);
    BufferedImage bi;
    try{
        bi = ImageIO.read(file);
    }catch(javax.imageio.IIOException e){
        if(request.getParameter("fi") != null){
            file = new File(context.getInitParameter("ImgPath") + "placeholder/150x80.png");
        }else if (request.getParameter("li") != null){
            file = new File(context.getInitParameter("ImgPath") + "placeholder/150x80.png");
        }

        bi = ImageIO.read(file);
    }

    OutputStream outImg = response.getOutputStream();
    File cacheDir = new File(context.getInitParameter("ImgPath") + "cache");
    try {
        ImageIO.setCacheDirectory(cacheDir);
        ImageIO.write(bi, "png", outImg);
    } catch (Exception ex) {

    }

    outImg.close();

1 个答案:

答案 0 :(得分:2)

问题:您的tomcat安装失败在启动时创建 temp 文件夹或临时文件夹不可写

解决方案:确保\ temp下存在临时文件夹并且它是可写的。

您可以手动创建

您可以通过在CATALINA_TMPDIR(windows)或catalina.bat h(linux)中设置catalina.s环境变量的值来覆盖Tomcat的默认临时文件夹位置

#   CATALINA_TMPDIR (Optional) Directory path location of temporary directory
#                   the JVM should use (java.io.tmpdir).  Defaults to
#                   $CATALINA_BASE/temp.