Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between InputStream and ByteArrayInputStream?

The following code is extracted from the java web start chapter of the core java volume 1.

     ByteArrayOutputStream out = new ByteArrayOutputStream();
     PrintStream printOut = new PrintStream(out);
     printOut.print(panel.getText());
     //panel.getText() return a String
     InputStream data = new ByteArrayInputStream(out.toByteArray());
     FileSaveService service = (FileSaveService) ServiceManager
           .lookup("javax.jnlp.FileSaveService");
     service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");

There are four objects created ,the stream is redirected three times. Is there any other methods to write data to a file by using jnlp api? what's the difference between InputStream and ByteArrayInputStream?

like image 976
scobur Avatar asked Dec 01 '12 03:12

scobur


2 Answers

ByteArrayInputStream and ByteArrayOututStream are in-memory implementations for use when you want to temporarily store the data in memory in a stream-like fashion, then pump it out again somewhere else.

For example, let's assume you have a method that expects an input stream as a parameter, eg

public Document parseXml(InputStream in) // build an XML document from data read in

but you want to send the contents of say a String to it. Then you'd use a ByteArrayInputStream and fill it with the contents of your String and pass the ByteArrayInputStream to the method.


An example of an ByteArrayOutputStream usage might be if a method writes to an output stream, but you just want to capture the result and get it directly.

like image 86
Bohemian Avatar answered Sep 19 '22 18:09

Bohemian


The InputStream is an abstract class and ByteArrayInputStream is a concrete class of InputStream and offers its own implementation of the abstract idea given by (InputStream),

In Addition :

  • A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.
  • An internal counter keeps track of the next byte to be supplied by the read method.

Closing a ByteArrayInputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

From Java Docs public class ByteArrayInputStream extends InputStream

like image 38
Yugansh Avatar answered Sep 18 '22 18:09

Yugansh