java - DataOutputStream to Array -
is there way write dataoutputstream content array
or string
regardless type of data contains?
dataoutputstream output = new dataoutputstream(new bufferedoutputstream(new fileoutputstream(string datapath)));
thanks
use bytearrrayoutputstream.
https://docs.oracle.com/javase/7/docs/api/java/io/bytearrayoutputstream.html
bytearrayoutputstream baos = new bytearrayoutputstream(); outputstream os = new dataoutputstream(baos); os.write(...); byte[] data = baos.tobytearray(); string dataasstring = new string(data, "utf-8"); // or whatever encoding using
you may use following strategy well:
class compositeoutputstream implements outputstream { private outputstream first,second; public compositeoutputstream(outputstream first, outputstream second) { this.first = first; this.second=second; } public void write(int b) throws ioexception { first.write(b); second.write(b); } // etc. }
use with:
bytearrayoutputstream baos = new bytearrayoutputstream(); outputstream os = new compositeoutputstream(new dataoutputstream(...), baos); os.write(...); byte[] data = baos.tobytearray(); string dataasstring = new string(data, "utf-8"); // or whatever encoding using // etc.
the "baos" "mirror" of what's got written original dataoutputstream
you still need handle exceptions correctly, , carefull amount of data written (holding in memory may lead out of memory), etc.
Comments
Post a Comment