简体   繁体   English

如何在不使用文件的情况下写入虚拟 DataOutputStream?

[英]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.我正在使用一个特定的库(不幸的是无法避免),它使用接收 DataOutputStream 作为输入的实用程序 function 将 class 中的一些信息写入文件。
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).我想将结果文件的内容作为字符串获取,而无需实际创建文件并将其写入其中,因为写入可能非常“繁重”(1000 多行)。
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?这是否可以通过使用虚拟 DataOutputStream 或其他方法来实现,而无需创建临时文件并从那里读取结果?

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. PS:实际写入 DataOutputStream 的最终方法会不时更改,所以我不希望每次都复制粘贴它并重做它。

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. 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稍后使用.toString()方法。

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 .如果收集的字节的编码与系统默认编码不匹配,您可能必须指定一个 Charset 作为toString的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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