how to use ByteArrayOutputStream and DataOutputStream simultaneously (Java)

后端 未结 6 697
花落未央
花落未央 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: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.

提交回复
热议问题