Read the data into a memory buffer

This is the easiest approach if your data easily fit into memory. I don't recommend this approach if the data you're reading is more than 20% of your total memory (because your heap needs space for other objects, and if you're in a web application 10-15 simultaneous users that allocate hundreds of megabytes can easily eat up all your memory). Plus you may be doing some operation on memory buffer m that force the JVM in creating copies of the buffer itself.

This approach also supports multiple reads of the same data:

Our original problem:

   OutputStream out = ?; //what to put here?
   InputStream in = ?;

   LibraryClass1.writeDataToTheOutputStream(out);
   ???
   LibraryClass2.processDataFromInputStream(in);

will become:

  ByteArrayOutputStream out = new ByteArrayOutputStream();

  //write data on your OutputStream here
  writeDataToTheOutputStream(out);

  byte[] data = out.toByteArray();
  ByteArrayInputStream istream = new ByteArrayInputStream(data);
  processDataFromInputStream(istream);
  //eventually you can use it twice:
  //processAgainDataFromInputSream(new ByteArrayInputStream(data));

Next we'll see how to save the data to a file.

Home Implementations

File buffer Next