daydreamer
daydreamer

Reputation: 91969

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

Upvotes: 5

Views: 26256

Answers (5)

harshit
harshit

Reputation: 7951

Try this( IOUtils is commons-io)

byte[] bytes = IOUtils.toByteArray(instream);

Upvotes: 3

Reimeus
Reimeus

Reputation: 159784

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

Upvotes: 3

obataku
obataku

Reputation: 29646

Why not try something like this?

@Test
public void testStreamBytes()
    throws PersistenceException, IOException, ClassNotFoundException {
  final String uniqueId = "TestString";
  final byte[] written = uniqueId.getBytes();
  final byte[] read = new byte[written.length];
  try (final OutputStream outStream = fileService.getOutputStream(uniqueId)) {
    outStream.write(written);
  }
  try (final InputStream inStream = fileService.getInputStream(uniqueId)) {
    int rd = 0;
    final int n = read.length;
    while (rd <= (rd += inStream.read(read, rd, n - rd)))
      ;
  }
  assertEquals(written, read);
}

Upvotes: -1

Amit Deshpande
Amit Deshpande

Reputation: 19185

You can read from inputstream and write on ByteArrayOutputStream then use toByteArray() method to convert it to byte array.

Upvotes: 1

Brian
Brian

Reputation: 17309

Java doesn't provide exactly what you want, but you could wrap the streams you're using with something like a PrintWriter and Scanner:

new PrintWriter(outStream).print(uniqueId);
String readId = new Scanner(inStream).next();
assertEquals(uniqueId, readId);

Upvotes: 0

Related Questions