woky
woky

Reputation: 4936

Java SAXParser - keep InputStream open

I've a BufferedInputStream from which I want to parse XML with SAXParser but then reuse it again (eg. mark(int) & reset()). However this stream is closed in parse() method. Is it possible to somehow tell SAXParser to leave it open? The last resort is to wrap this stream with un-closeable stream.

Thank you.

Upvotes: 4

Views: 3934

Answers (3)

user25615362
user25615362

Reputation: 1

I use the follwing wrapper for the InputStream to prevent the parser from closing the original stream:

    private static class InputStreamWrapper extends InputStream {
    private InputStream input;

    public InputStreamWrapper(InputStream input) {
        this.input = input;
    }

    @Override
    public int read() throws IOException {
        return input.read();
    }

    // Must be overriden for better performance
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return input.read(b, off, len);
    }

    @Override
    public void close() {
    }
}

The wrapper is used like saxParser.parse(new InputStreamWrapper(input), handler).

Putting the InputStream in an InputSource does not help. This is done internally by the SAX parser.

Upvotes: 0

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53647

You can pass InputSource object rather than InputStream object to SAXParser

sample code

SAXParser parser = // saxpaser object
        InputSource isource = new InputSource();
        InputStream istream = //your inputstream
        isource.setByteStream(istream);
        parser.parse(isource, handler);

Upvotes: -1

OldCurmudgeon
OldCurmudgeon

Reputation: 65793

How about something like:

class WontCloseBufferedInputStream extends BufferedInputStream {
  public void close () {
    // Do nothing.
  }

  public void reallyClose() {
    super.close ();
  }
}

Upvotes: 8

Related Questions