Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between InputSource and InputStream? [duplicate]

What is the difference between using InputSource and InputStream when I am parsing xml. I saw both examples in some tutorials

without InputSource:

InputStream is;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbFactory.newDocumentBuilder();
Document document = db.parse(is);

and with InputSource, where is the difference

DocumentBuilder db = dbFactory.newDocumentBuilder();
InputSource inputSource = new InputSource(is);
Document document = db.parse(inputSource);

So is there any difference in performance? Or in something else?

like image 892
Pauli Avatar asked Aug 21 '14 15:08

Pauli


People also ask

What is InputSource?

public InputSource(Reader characterStream) Create a new input source with a character stream. Application writers should use setSystemId() to provide a base for resolving relative URIs, and may use setPublicId to include a public identifier. The character stream shall not include a byte order mark.

What is InputStream and OutputStream?

In Java, streams are the sequence of data that are read from the source and written to the destination. An input stream is used to read data from the source. And, an output stream is used to write data to the destination.

Why we use InputStream?

1.1 InputStream: InputStream is an abstract class of Byte Stream that describe stream input and it is used for reading and it could be a file, image, audio, video, webpage, etc. it doesn't matter. Thus, InputStream read data from source one item at a time.

What is use of InputStream In Java?

The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy of classes to deal with Input and Output streams.


1 Answers

An InputSource can read from an InputStream, but it can also read from a Reader or direct from a URL (opening the stream itself). Parsing from an InputStream is equivalent to parsing from a new InputSource(theStream).

If the file you want to parse makes reference to an external DTD or any external entities by relative URIs then you can't parse it from a plain InputStream, as the parser doesn't know the base URL it should use to resolve these relative paths. In that case you will need to construct an InputSource from the stream and use setSystemId to set the base URI and then parse from that source, rather than simply passing the stream direct to the parser.

like image 57
Ian Roberts Avatar answered Sep 17 '22 18:09

Ian Roberts