Skip to content

Commit

Permalink
Refactor parseToString method to use try-with-resources (#1946)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
ldh5574 authored and THausherr committed Sep 12, 2024
1 parent 4dccdd6 commit 5e33495
Showing 1 changed file with 4 additions and 6 deletions.
10 changes: 4 additions & 6 deletions tika-core/src/main/java/org/apache/tika/Tika.java
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down

0 comments on commit 5e33495

Please sign in to comment.