简体   繁体   English

如何存储到Byte或Byte数组中

[英]How to store into Byte or Byte array

This message is coming from external system and this is coming as bytes, I have to use it in my Java code. 该消息来自外部系统,并且以字节为单位,我必须在Java代码中使用它。 I am taking it as a byte and converting to String . 我将其作为一个字节并转换为String

Can anyone help me to accept it as byte only instead of taking it to string and converting to byte. 任何人都可以帮助我仅将其作为字节接受,而不是将其带入字符串并转换为字节。

Here is the output from that external system till equals to: 这是该外部系统的输出,直到等于:

wcLDxMXGx8jJ0fHy8/T1AHsSNFw= wcLDxMXGx8jJ0fHy8 / T1AHsSNFw =

I want to store it either in byte or byte[] . 我想将其存储在bytebyte[]

I have tried doing it myself but it says error at = . 我已经尝试过自己做,但是error at = I have to use it as byte only as taking it as String and then converting to byte will be problematic and not as expected. 我必须仅将其用作String ,然后将其用作字节,然后转换为byte将是有问题的,而不是预期的那样。

You can use the class javax.xml.bind.DatatypeConverter (since Java SE 6 update 3): 您可以使用类javax.xml.bind.DatatypeConverter (自Java SE 6更新3开始):

Code : 代码

public static void main(String[] args) {
    String str = "wcLDxMXGx8jJ0fHy8/T1AHsSNFw=";
    byte[] array = DatatypeConverter.parseBase64Binary(str);
    System.out.println(Arrays.toString(array));
}

Output : 输出

[-63, -62, -61, -60, -59, -58, -57, -56, -55, -47, -15, -14, -13, -12, -11, 0, 123, 18, 52, 92]
try (ByteArrayInputStream bais = new ByteArrayInputStream()) {
    try (InputStream externalSource = ...)) {
        for (;;) {
            int b = externalSource.read();
            if (b == -1 || b == 'I') { // End of file or ASCII I
                break;
            }
            bais.write((byte) b);
        }
    }
    byte[] bytes = bais.toByteArray();
}

There is a "till" in your question, which I translated into a condition || b == 'I' 您的问题中有一个“耕种”,我将其翻译为条件|| b == 'I' || b == 'I' . || b == 'I' You probably did not intend that. 您可能不打算这样做。 Maybe you used = instead of == . 也许您使用=而不是==

The above reads an int which is -1 when end-of-file, a byte value otherwise. 上面的文件末尾读取一个为-1的int,否则为一个字节值。

The try-with-resources syntax ensures that externalSource and bais are closed. try-with-resources语法可确保关闭externalSourcebais

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

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