简体   繁体   中英

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 .

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

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 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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