我想测试我写入 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/