Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read bytes from InputStream?

I want to test that the bytes I write to OutputStream(a file OuputStream) is same as I read from same InputStream.

Test looks like

  @Test
    public void testStreamBytes() throws PersistenceException, IOException, ClassNotFoundException {
        String uniqueId = "TestString";
        final OutputStream outStream = fileService.getOutputStream(uniqueId);
        new ObjectOutputStream(outStream).write(uniqueId.getBytes());
        final InputStream inStream = fileService.getInputStream(uniqueId);
    }

I realized that InputStream doesn't have getBytes().

How can I test something like

assertEquals(inStream.getBytes(), uniqueId.getBytes())

Thank you

like image 564
daydreamer Avatar asked Aug 31 '12 22:08

daydreamer


1 Answers

You could use ByteArrayOutputStream

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[16384];

while ((nRead = inStream.read(data, 0, data.length)) != -1) {
  buffer.write(data, 0, nRead);
}

buffer.flush();

and check using:

assertEquals(buffer.toByteArray(), uniqueId.getBytes());
like image 187
Reimeus Avatar answered Oct 23 '22 09:10

Reimeus