简体   繁体   中英

How to write to a dummy DataOutputStream without using files?

I'm using a specific library (unfortunately can't be avoided) that writes some information from a class to a file using a utility function that receives a DataOutputStream as the input.
I would like to get the resulting file's content as a String without actually creating a file and writing into it as the writing can be pretty "taxing" (1000+ lines).
Is this possible to do by using a dummy DataOutputStream or some other method and without resorting to creating a temporary file and reading the result from there?

PS: the final method that actually writes to the DataOutputStream changes from time to time so I would prefer not actually copy-paste it and redo it every time.

As java.io.DataOutputStream wraps around just any other java.io.OutputStream (you have to specify an instance in the constructor) I would recommend that you use a java.io.ByteArrayOutputStream to collect the data in-memory and get the String of that later with the .toString() method.

Example:

ByteArrayOutputStream inMemoryOutput = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(inMemoryOutput);

// use dataOutputStream here as intended

// and then get the String data
System.out.println(inMemoryOutput.toString());

If the encoding of the collected bytes does not match the system default encoding, you might have to specify a Charset as parameter of the toString .

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