how to use ByteArrayOutputStream and DataOutputStream simultaneously (Java)

后端 未结 6 687
花落未央
花落未央 2020-12-14 22:54

I\'m having quite a problem here, and I think it is because I don\'t understand very much how I should use the API provided by Java.

I need to write an int

相关标签:
6条回答
  • 2020-12-14 23:12

    You don´t need more like this

    Example exampleExample = method(example); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); marshaller.marshal(exampleExample , baos);
    Message message = MessageBuilder.withBody(baos.toByteArray()).build();
    
    0 讨论(0)
  • Use the former case - wrap DataOutputStream around the ByteArrayOutputStream. Just make sure you save the reference to the ByteArrayOutputStream. When you are finished, close() or at least flush() the DataOutputStream and then use the toByteArray method of the ByteArrayOutputStream.

    0 讨论(0)
  • 2020-12-14 23:14

    Could you make a variable to hold on to the ByteArrayOutputStream and pass it into the DataOutputStream.

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    dos.writeInt(1);
    byte[] result = dos.toByteArray();
    
    0 讨论(0)
  • 2020-12-14 23:15

    You could use a stream approach if you connect your outputstream to an inputstream through a PipedInputStream/PipetOutputStream. Then you will consume the data from the inputstream.

    Anyway if what you need to do is simple and doesn't not require a stream approach I would use a java.nio.ByteBuffer on which you have

    • put(byte[] src) for your byte[]
    • putInt(int value)
    • and byte[] array() to get the content
    0 讨论(0)
  • 2020-12-14 23:20

    The Integer class has a method to get the byte value of an int. Integer.byteValue()

    0 讨论(0)
  • 2020-12-14 23:29

    Like this:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream w = new DataOutputStream(baos);
    
    w.writeInt(100);
    w.write(byteArray);
    
    w.flush();
    
    byte[] result = baos.toByteArray();
    

    Actually your second version will not work at all. DataOutputStream requires an actual target stream in which to write the data. You can't do new DataOutputStream(). There isn't actually any constructor like that.

    0 讨论(0)
提交回复
热议问题