From 78eb52afa234963943a825e0e9d366d125e76263 Mon Sep 17 00:00:00 2001 From: DHL <46510929+ldh5574@users.noreply.github.com> Date: Thu, 12 Sep 2024 12:44:16 +0900 Subject: [PATCH] Refactor parseToString method to use try-with-resources (#1946) try-with-resources is used to automatically handle closing the InputStream, ensuring that it is always closed properly without the need for a finally block --- tika-core/src/main/java/org/apache/tika/Tika.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/tika-core/src/main/java/org/apache/tika/Tika.java b/tika-core/src/main/java/org/apache/tika/Tika.java index 22811f9c0b..2f17de6451 100644 --- a/tika-core/src/main/java/org/apache/tika/Tika.java +++ b/tika-core/src/main/java/org/apache/tika/Tika.java @@ -519,17 +519,15 @@ public String parseToString(InputStream stream, Metadata metadata) public String parseToString(InputStream stream, Metadata metadata, int maxLength) throws IOException, TikaException { WriteOutContentHandler handler = new WriteOutContentHandler(maxLength); - try { - ParseContext context = new ParseContext(); - context.set(Parser.class, parser); - parser.parse(stream, new BodyContentHandler(handler), metadata, context); + ParseContext context = new ParseContext(); + context.set(Parser.class, parser); + try (InputStream autoCloseStream = stream) { + parser.parse(autoCloseStream, new BodyContentHandler(handler), metadata, context); } catch (SAXException e) { if (!WriteLimitReachedException.isWriteLimitReached(e)) { // This should never happen with BodyContentHandler... throw new TikaException("Unexpected SAX processing failure", e); } - } finally { - stream.close(); } return handler.toString(); }