简体   繁体   English

如何从InputStream读取字节?

[英]How do I read bytes from InputStream?

I want to test that the bytes I write to OutputStream (a file OuputStream) is same as I read from same InputStream . 我想测试我写入OutputStream (文件OuputStream)的字节与我从同一个InputStream读取的字节相同。

Test looks like 测试看起来像

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

I realized that InputStream doesn't have getBytes() . 我意识到InputStream没有getBytes()

How can I test something like 我该怎么测试类似的东西

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

Thank you 谢谢

试试这个(IOUtils是commons-io)

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

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

and check using: 并检查使用:

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

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

Java doesn't provide exactly what you want, but you could wrap the streams you're using with something like a PrintWriter and Scanner : Java并不能提供您想要的内容,但您可以使用PrintWriterScanner类的内容包装您正在使用的流:

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

Why not try something like this? 为什么不尝试这样的事情呢?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM