简体   繁体   中英

DataOutputStream to Array

Is there any way to write DataOutputStream content to an Array or a String regardless which type of data it 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 you are using

You may use the following strategy as 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 you are using
// etc.

The "baos" is only a "mirror" of what's got written to your original DataOutputStream

You still need to handle exceptions correctly, and be carefull about the amount of data written (holding everything in memory may lead to out of memory), etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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