@@ -138,10 +138,14 @@ public static Document load(Path path, @Nullable String charsetName, String base
138138 public static StreamParser streamParser (Path path , @ Nullable Charset charset , String baseUri , Parser parser ) throws IOException {
139139 StreamParser streamer = new StreamParser (parser );
140140 String charsetName = charset != null ? charset .name () : null ;
141- DataUtil .CharsetDoc charsetDoc = DataUtil .detectCharset (openStream (path ), charsetName , baseUri , parser );
142- BufferedReader reader = new BufferedReader (new InputStreamReader (charsetDoc .input , charsetDoc .charset ), DefaultBufferSize );
143- streamer .parse (reader , baseUri ); // initializes the parse and the document, but does not step() it
144-
141+ try {
142+ DataUtil .CharsetDoc charsetDoc = DataUtil .detectCharset (openStream (path ), charsetName , baseUri , parser );
143+ BufferedReader reader = new BufferedReader (new InputStreamReader (charsetDoc .input , charsetDoc .charset ), DefaultBufferSize );
144+ streamer .parse (reader , baseUri ); // initializes the parse and the document, but does not step() it
145+ } catch (IOException e ) {
146+ streamer .close ();
147+ throw e ;
148+ }
145149 return streamer ;
146150 }
147151
@@ -151,10 +155,13 @@ private static ControllableInputStream openStream(Path path) throws IOException
151155 InputStream stream = Channels .newInputStream (byteChannel );
152156 String name = Normalizer .lowerCase (path .getFileName ().toString ());
153157 if (name .endsWith (".gz" ) || name .endsWith (".z" )) {
154- final boolean zipped = (stream .read () == 0x1f && stream .read () == 0x8b ); // gzip magic bytes
155- byteChannel .position (0 ); // reset to start of file
156- if (zipped ) {
157- stream = new GZIPInputStream (stream );
158+ try {
159+ final boolean zipped = (stream .read () == 0x1f && stream .read () == 0x8b ); // gzip magic bytes
160+ byteChannel .position (0 ); // reset to start of file
161+ if (zipped ) stream = new GZIPInputStream (stream );
162+ } catch (IOException e ) {
163+ stream .close (); // error during our first read; close the stream and cascade close byteChannel
164+ throw e ;
158165 }
159166 }
160167 return ControllableInputStream .wrap (stream , 0 );
0 commit comments