Search code examples
javatomcattemp

Store a file temporarily in side temp folder of tomcat


Can you please tell me any Java code that I can use to store a file inside Tomcat's temp folder so that once it is used (downloaded) it will be deleted automatically?


Solution

  • Well there are Many ways to do this, you should explore the CATALINA_HOME Environmental Variable as this Points to the Tomcat Installation Directory.

    Update *Try this:*

    @SuppressWarnings("restriction")
     BASE64Decoder decoder = new BASE64Decoder(); // Decode encoded string into original byte array
    System.out.println("in try "); 
    System.out.println("imagestring "+ imageString);
    byte[] decoded = decoder.decodeBuffer(imageString);
    System.out.println("image"+ decoded); 
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(decoded));
    
    File f = new File(System.getenv("CATALINA_HOME") + "/temp");//TomcatHome director/tempfolder
    System.out.println(f.getAbsolutePath());//debug like this
    if(!f.exists()){
    f.mkdir();//make temp folder if it does not exist
    }
    ImageIO.write(image, "jpg",new File(f.getAbsolutePath() + "/yourimagename.jpg"));//write image to to the temp folder
    }
    //do some other Processing
    File file = new File(f.getAbsolutePath() + "/yourimagename.jpg");
    if(file.exists()){
    file.delete();
     }
    

    After processing , you can delete it in the usual way file.delete();

    You need to make sure that the environmental variable CATALINA_HOME Points to Tomcat base directory.