0

I have a binary file, in my jar, and I want to slurp its contents in binary mode, not into a string of characters. Following this example

private byte[] readBinaryFile(String fileName) throws IOException {
    InputStream input = getClass().getResourceAsStream(fileName);
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    for (int read = input.read(); read >= 0; read = input.read())
        output.write(read);

    byte[] buffer = output.toByteArray();

    input.close ();
    output.close();

    return buffer;
}

It's pretty trivial, but the calling context is expecting and Object. How do I pass this binary contents back to the caller, but not as a primitive array? I am trying to deliver this binary data as a response to a web service using jaxrs.

David Williams
  • 8,388
  • 23
  • 83
  • 171
  • 2
    A byte array *is* an object. It's extremely unclear what's wrong here... Also note that reading a single byte at a time can be pretty inefficient. It would usually be better to read blocks at a time, via a buffer. Oh, and either use a `finally` block to close each of the input and output streams... or a try-with-resources statement if you're using Java 7. – Jon Skeet Oct 20 '13 at 16:41
  • Excuse me, you are right, this is not a real question – David Williams Oct 20 '13 at 16:58
  • Jon, can you point me to an example with a buffer? – David Williams Oct 20 '13 at 17:04
  • Here's an example: http://stackoverflow.com/a/5924132/22656 – Jon Skeet Oct 20 '13 at 17:08

1 Answers1

0

As @Jon notes, the caller should be just fine:

byte[] b = new byte[10];
Object o = b;

That works because as he points out a byte[] is an instance of Object.

Don't confuse bytes themselves, which are indeed primitives, with the array. All arrays are objects no matter what they contain.

So the caller should receive his Object and then send it back to his caller as application/octet-stream.

Vidya
  • 29,932
  • 7
  • 42
  • 70