4

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.

3 Answers 3

8

How about something like:

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

  public void reallyClose() {
    super.close ();
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am interested to know why you see this as a last resort. It does exactly what you want.
Because it's ugly. IMO library shouldn't close passed in InputStream/Reader.
0

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.

1 Comment

just change "vom" to "from"
-1

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);

2 Comments

Is the InputSource closed when the parser completes? If so this is unhelpful.
But then this post doesn't solve the problem neither hints the solution :o)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.