如何从InputStream读取字节?

时间:2012-08-31 22:12:02

标签: java inputstream

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

谢谢

5 个答案:

答案 0 :(得分:2)

您可以使用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());

答案 1 :(得分:1)

试试这个(IOUtils是commons-io)

byte[] bytes = IOUtils.toByteArray(instream);

答案 2 :(得分:1)

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

答案 3 :(得分:0)

Java并没有提供您想要的内容,但您可以使用PrintWriterScanner之类的内容包装您正在使用的流:

new PrintWriter(outStream).print(uniqueId);
String readId = new Scanner(inStream).next();
assertEquals(uniqueId, readId);

答案 4 :(得分:-2)

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

@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);
}