有没有办法将DataOutputStream内容写入Array
或String
,无论它包含哪种类型的数据?
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(String dataPath)));
由于
答案 0 :(得分:1)
使用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
您也可以使用以下策略:
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.
}
使用:
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.
“baos”只是写入原始DataOutputStream的“镜像”
您仍然需要正确处理异常,并且要小心写入的数据量(将所有内容保存在内存中可能会导致内存不足)等。