如何从InputStream中读取字节?

5

我想测试我写到OutputStream(文件输出流)的字节与我从同一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())

谢谢你。

补充一点:String#getBytes() 在将字符串编码为字节时假定系统默认字符集,不要忘记这一点。由于只能通过使用字符集将每个字符编码为一个或多个字节来实现“仅获取字符串的字节”,因此没有其他方法。 - klaar
5个回答

3
尝试这个(IOUtils是commons-io库)
byte[] bytes = IOUtils.toByteArray(instream);

2
我相信IOUtils是commons-io,Java是否提供了类似的东西? - daydreamer
1
@daydreamer 是的,可以使用 ByteArrayOutputStream - obataku

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());

1

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


0

Java并没有提供你需要的东西,但是你可以使用像PrintWriterScanner这样的东西来包装你正在使用的流:

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

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

不起作用。您必须独立于上次读取计数来提前偏移量。 - user207421

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接