简体   繁体   English

Java:将JAR中的二进制文件读入标量,而不是原始字节[]

[英]Java: Read Binary File From JAR into Scalar, Not Primitive byte[]

I have a binary file, in my jar, and I want to slurp its contents in binary mode, not into a string of characters. 我的jar中有一个二进制文件,我想以二进制模式(而不是字符串)吸收其内容。 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. 我正在尝试将此二进制数据作为对使用jaxrs的Web服务的响应进行传递。

As @Jon notes, the caller should be just fine: 正如@Jon所指出的,调用方应该没问题:

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

That works because as he points out a byte[] is an instance of Object . 之所以可行,是因为他指出byte[]Object一个实例。

Don't confuse bytes themselves, which are indeed primitives, with the array. 不要将bytes本身(确实是基元)与数组混淆。 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 . 因此,调用者应接收其Object ,然后将其作为application/octet-stream传回给其调用者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM