Jürgen K.
Jürgen K.

Reputation: 3487

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

Upvotes: 0

Views: 2601

Answers (1)

spi
spi

Reputation: 636

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.

Upvotes: 2

Related Questions