gpt4 book ai didi

java - 如何从 InputStream 读取字节?

转载 作者:搜寻专家 更新时间:2023-11-01 02:50:28 24 4
gpt4 key购买 nike

我想测试我写入 OutputStream(一个文件 OuputStream)的字节是否与我从同一个 InputStream 读取的字节相同。

测试看起来像

  @Test
public void testStreamBytes() throws PersistenceException, IOException, ClassNotFoundException {
String uniqueId = "TestString";
final OutputStream outStream = fileService.getOutputStream(uniqueId);
new ObjectOutputStream(outStream).write(uniqueId.getBytes());
final InputStream inStream = fileService.getInputStream(uniqueId);
}

我意识到 InputStream 没有 getBytes()

我怎样才能测试类似的东西

assertEquals(inStream.getBytes(), uniqueId.getBytes())

谢谢

最佳答案

你可以使用 ByteArrayOutputStream

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[16384];

while ((nRead = inStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}

buffer.flush();

并检查使用:

assertEquals(buffer.toByteArray(), uniqueId.getBytes());

关于java - 如何从 InputStream 读取字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12223072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com