From 8b840258411f84d721bcdca2b44d4d5fe569b2f8 Mon Sep 17 00:00:00 2001 From: Luis Nassif Date: Wed, 14 Jul 2021 15:17:38 -0300 Subject: [PATCH] #415: better close resources in EmlViewer --- .../ui/fileViewer/frames/EmailViewer.java | 28 +++++++++---------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/iped-viewers/iped-viewers-impl/src/main/java/dpf/sp/gpinf/indexer/ui/fileViewer/frames/EmailViewer.java b/iped-viewers/iped-viewers-impl/src/main/java/dpf/sp/gpinf/indexer/ui/fileViewer/frames/EmailViewer.java index 804188e24d..e797110013 100644 --- a/iped-viewers/iped-viewers-impl/src/main/java/dpf/sp/gpinf/indexer/ui/fileViewer/frames/EmailViewer.java +++ b/iped-viewers/iped-viewers-impl/src/main/java/dpf/sp/gpinf/indexer/ui/fileViewer/frames/EmailViewer.java @@ -211,8 +211,7 @@ private String decodeIfUtf8(String value) { return value; } - private void createHeader(OutputStream outStream) throws IOException { - OutputStreamWriter writer = new OutputStreamWriter(outStream, bodyCharset); + private void createHeader(OutputStreamWriter writer) throws IOException { writer.write(""); //$NON-NLS-1$ writer.write(""); //$NON-NLS-1$ @@ -379,14 +378,20 @@ public void body(BodyDescriptor body, InputStream is) throws MimeException, IOEx public void endMessage() throws MimeException { try { - previewFile = File.createTempFile("message", ".html"); //$NON-NLS-1$ //$NON-NLS-2$ + previewFile = File.createTempFile("message", ".html"); previewFile.deleteOnExit(); - OutputStream outStream = new BufferedOutputStream(new FileOutputStream(previewFile)); - createHeader(outStream); + } catch (IOException e1) { + throw new RuntimeException(e1); + } + + Charset charset = Charset.forName(bodyCharset); + try (OutputStream outStream = new BufferedOutputStream(new FileOutputStream(previewFile)); + OutputStreamWriter writer = new OutputStreamWriter(outStream, charset)) { + + createHeader(writer); Set inlined = new HashSet<>(); if (bodyFile != null) { - Charset charset = Charset.forName(bodyCharset); String body = new String(Files.readAllBytes(bodyFile.toPath()), charset); // handle inline images for (Entry e : attachments.entrySet()) { @@ -396,12 +401,10 @@ public void endMessage() throws MimeException { } body = newBody; } - outStream.write(body.getBytes(charset)); + writer.write(body); bodyFile.delete(); } - OutputStreamWriter writer = new OutputStreamWriter(outStream, bodyCharset); - inlined.stream().forEach(a -> attachments.remove(a)); for (AttachInfo attach : attachments.values()) { if (attach.mime.startsWith("image")) { //$NON-NLS-1$ @@ -421,14 +424,9 @@ public void endMessage() throws MimeException { } writer.flush(); - InputStream stream = new FileInputStream(attach.tmpFile); - IOUtil.copiaArquivo(stream, outStream); - stream.close(); + Files.copy(attach.tmpFile.toPath(), outStream); } } - writer.flush(); - - outStream.close(); } catch (IOException e) { e.printStackTrace();