3
\$\begingroup\$

I have the following code that that writes large images to disk. My application server is running out of memory and I'm wondering if I could somehow optimize the following:

public void writeImgToDisk(byte[] base64AttachmentInBytes, String dmxi){

        String destinationAndFileName  = "";
        String fileNameMinusExtension = getCurrentTimeStampForFileNaming();
        String extension="";
        try {


               TikaConfig config = TikaConfig.getDefaultConfig();
               InputStream stream = new ByteArrayInputStream(base64AttachmentInBytes);

               MediaType mediaType = config.getMimeRepository().detect(stream, new Metadata());
               MimeType mimeType;


            try {
                mimeType = config.getMimeRepository().forName(mediaType.toString());
                extension = mimeType.getExtension();
                System.out.println("Extension is:"+ extension);

                File folder  = new File("Z:\\images\\"+ sref);
                if (!folder.exists()){
                    folder.mkdir();
                }
                destinationAndFileName  = "Z:\\images\\"+ dmxi + "\\" + fileNameMinusExtension+ extension;

                System.out.println("destinationAndFileName is:"+ destinationAndFileName);
            } catch (MimeTypeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            InputStream input = new ByteArrayInputStream(base64AttachmentInBytes);
            OutputStream output = new FileOutputStream(destinationAndFileName);
            IOUtils.copy(input, output);


            System.out.println("It was written..");  
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

This works but its the cause of a bottleneck during high volume calls.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You're not closing the output stream! If that doesn't fix your issue, you'll have to post more contextual code, because after you free the output stream, the rest of this method should just free its resources after it is done.

\$\endgroup\$
2
  • \$\begingroup\$ I'm assuming IOUtils.closeQuietly() should do the job ? \$\endgroup\$ Commented Jun 28, 2016 at 12:17
  • \$\begingroup\$ @TonyDerrum yeah, that'll do \$\endgroup\$
    – Pimgd
    Commented Jun 28, 2016 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.