【问题标题】:How do I read bytes from InputStream?如何从 InputStream 中读取字节?
【发布时间】:2012-08-31 22:12:02
【问题描述】:

我想测试我写入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() 在将字符串编码为字节时假定系统默认字符集,不要忘记。没有办法“只从字符串中获取字节”,因为这只能通过使用字符集将每个字符编码为一个或多个字节来实现。

标签: java inputstream


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      试试这个(IOUtils 是 commons-io)

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

      【讨论】:

      • 我相信 IOUtils 是 commons-io,Java 不提供类似的东西吗?
      • @daydreamer 是的,使用ByteArrayOutputStream
      【解决方案4】:

      Java 不能提供您真正想要的,但您可以使用 PrintWriterScanner 之类的东西包装您正在使用的流:

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

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

        • 不起作用。您必须独立于上次读取计数来提高偏移量。
        猜你喜欢
        • 2023-03-30
        • 1970-01-01
        • 2011-08-07
        • 2012-12-25
        • 2020-03-11
        • 2018-06-28
        • 2018-02-17
        • 2012-03-03
        相关资源
        最近更新 更多