0
votes

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.

1
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
Excuse me, you are right, this is not a real question - David Williams
Jon, can you point me to an example with a buffer? - David Williams

1 Answers

0
votes

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.