5

我想测试我写入的字节OutputStream(文件 OuputStream)是否与我从 same 中读取的字节相同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())

谢谢

4

5 回答 5

3

你可以使用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());
于 2012-08-31T22:28:27.630 回答
2

试试这个(IOUtils 是 commons-io)

byte[] bytes = IOUtils.toByteArray(instream);
于 2012-08-31T22:15:53.417 回答
1

您可以从输入流中读取并在 ByteArrayOutputStream 上写入,然后使用toByteArray()方法将其转换为字节数组。

于 2012-08-31T22:27:41.910 回答
0

Java 不能提供你想要的东西,但你可以用类似 aPrintWriter和的东西来包装你正在使用的流Scanner

new PrintWriter(outStream).print(uniqueId);
String readId = new Scanner(inStream).next();
assertEquals(uniqueId, readId);
于 2012-08-31T22:25:08.870 回答
-1

为什么不尝试这样的事情呢?

@Test
public void testStreamBytes()
    throws PersistenceException, IOException, ClassNotFoundException {
  final String uniqueId = "TestString";
  final byte[] written = uniqueId.getBytes();
  final byte[] read = new byte[written.length];
  try (final OutputStream outStream = fileService.getOutputStream(uniqueId)) {
    outStream.write(written);
  }
  try (final InputStream inStream = fileService.getInputStream(uniqueId)) {
    int rd = 0;
    final int n = read.length;
    while (rd <= (rd += inStream.read(read, rd, n - rd)))
      ;
  }
  assertEquals(written, read);
}
于 2012-08-31T22:29:48.127 回答