org.apache.commons.io.output.ByteArrayOutputStream类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(12.2k)|赞(0)|评价(0)|浏览(348)

本文整理了Java中org.apache.commons.io.output.ByteArrayOutputStream类的一些代码示例,展示了ByteArrayOutputStream类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ByteArrayOutputStream类的具体详情如下:
包路径:org.apache.commons.io.output.ByteArrayOutputStream
类名称:ByteArrayOutputStream

ByteArrayOutputStream介绍

[英]This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it.

The data can be retrieved using toByteArray() and toString().

Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

This is an alternative implementation of the java.io.ByteArrayOutputStreamclass. The original implementation only allocates 32 bytes at the beginning. As this class is designed for heavy duty it starts at 1024 bytes. In contrast to the original it doesn't reallocate the whole memory block but allocates additional buffers. This way no buffers need to be garbage collected and the contents don't have to be copied to the new buffer. This class is designed to behave exactly like the original. The only exception is the deprecated toString(int) method that has been ignored.
[中]此类实现了一个输出流,其中数据被写入字节数组。当数据写入缓冲区时,缓冲区会自动增长。
可以使用toByteArray()toString()检索数据。
关闭ByteArrayOutputStream无效。此类中的方法可以在流关闭后调用,而不会生成IOException。
这是java的另一种实现。木卫一。ByteArrayOutputStreamclass。最初的实现在开始时只分配32个字节。因为这个类是为重载设计的,所以它从1024字节开始。与原始版本不同,它没有重新分配整个内存块,而是分配额外的缓冲区。这样就不需要对缓冲区进行垃圾收集,也不必将内容复制到新的缓冲区。该类的行为与原始类完全相同。唯一的例外是被忽略的不推荐使用的toString(int)方法。

代码示例

代码示例来源:origin: commons-io/commons-io

@Test
public void testWrite_byteArrayToWriter_Encoding_nullEncoding() throws Exception {
  final ByteArrayOutputStream baout = new ByteArrayOutputStream();
  @SuppressWarnings("resource") // deliberately not closed
  final YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true);
  final Writer writer = new OutputStreamWriter(baout, "US-ASCII");
  IOUtils.write(inData, writer, (String) null);
  out.off();
  writer.flush();
  assertEquals("Sizes differ", inData.length, baout.size());
  assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray()));
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Prints this note into a writer.
 *
 * <p>
 * Technically, this method only works if the {@link Writer} to {@link OutputStream}
 * encoding is ASCII compatible.
 */
public void encodeTo(Writer out) throws IOException {
  out.write(encodeToBytes().toString());
}

代码示例来源:origin: apache/flume

int blobLength = 0;
int n = 0;
while ((n = in.read(buf, 0, Math.min(buf.length, maxBlobLength - blobLength))) != -1) {
 if (blob == null) {
  blob = new ByteArrayOutputStream(n);
 blob.write(buf, 0, n);
 blobLength += n;
 if (blobLength >= maxBlobLength) {
byte[] array = blob != null ? blob.toByteArray() : new byte[0];
Event event = EventBuilder.withBody(array, headers);
if (LOGGER.isDebugEnabled() && LogPrivacyUtil.allowLogRawData()) {
in.close();

代码示例来源:origin: commons-io/commons-io

/**
 * Fetches entire contents of an <code>InputStream</code> and represent
 * same data as result InputStream.
 * <p>
 * This method is useful where,
 * <ul>
 * <li>Source InputStream is slow.</li>
 * <li>It has network resources associated, so we cannot keep it open for
 * long time.</li>
 * <li>It has network timeout associated.</li>
 * </ul>
 * It can be used in favor of {@link #toByteArray()}, since it
 * avoids unnecessary allocation and copy of byte[].<br>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedInputStream</code>.
 *
 * @param input Stream to be fully buffered.
 * @param size the initial buffer size
 * @return A fully buffered stream.
 * @throws IOException if an I/O error occurs
 * @since 2.5
 */
public static InputStream toBufferedInputStream(final InputStream input, final int size)
    throws IOException {
  // It does not matter if a ByteArrayOutputStream is not closed as close() is a no-op
  @SuppressWarnings("resource")
  final ByteArrayOutputStream output = new ByteArrayOutputStream(size);
  output.write(input);
  return output.toInputStream();
}

代码示例来源:origin: gocd/gocd

public String toString(Document document) throws IOException {
  org.apache.commons.io.output.ByteArrayOutputStream outputStream = new org.apache.commons.io.output.ByteArrayOutputStream();
  XmlUtils.writeXml(document, outputStream);
  return outputStream.toString(StandardCharsets.UTF_8);
}

代码示例来源:origin: apache/hive

public static byte[] serializeJobConf(JobConf jobConf) {
 ByteArrayOutputStream out = new ByteArrayOutputStream();
 try {
  jobConf.write(new DataOutputStream(out));
 } catch (IOException e) {
  LOG.error("Error serializing job configuration: " + e, e);
  return null;
 } finally {
  try {
   out.close();
  } catch (IOException e) {
   LOG.error("Error closing output stream: " + e, e);
  }
 }
 return out.toByteArray();
}

代码示例来源:origin: commons-io/commons-io

@SuppressWarnings("resource") // 'in' is deliberately not closed
private void testCopy_inputStreamToOutputStreamWithBufferSize(final int bufferSize) throws Exception {
  InputStream in = new ByteArrayInputStream(inData);
  in = new YellOnCloseInputStream(in);
  final ByteArrayOutputStream baout = new ByteArrayOutputStream();
  final OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true);
  final long count = IOUtils.copy(in, out, bufferSize);
  assertEquals("Not all bytes were read", 0, in.available());
  assertEquals("Sizes differ", inData.length, baout.size());
  assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray()));
  assertEquals(inData.length,count);
}

代码示例来源:origin: jenkinsci/jenkins

@Override
public int read(byte b[], int off, int len) throws IOException {
  int r = in.read(b, off, len);
  if(r>0) {
    int sp = space();
    if(sp>0)
      side.write(b,off,Math.min(r, sp));
  }
  return r;
}

代码示例来源:origin: syncany/syncany

public void save(File file, List<CipherSpec> cipherSpecs, SaltedSecretKey masterKey) throws ConfigException {
  try {
    ByteArrayOutputStream plaintextRepoOutputStream = new ByteArrayOutputStream();
    Serializer serializer = new Persister();
    serializer.write(this, plaintextRepoOutputStream);
    CipherUtil.encrypt(new ByteArrayInputStream(plaintextRepoOutputStream.toByteArray()), new FileOutputStream(file), cipherSpecs, masterKey);
  }
  catch (Exception e) {
    throw new ConfigException("Cannot write repoTO (encrypted) to file " + file, e);
  }
}

代码示例来源:origin: com.googlecode.gwtquery/gwtquery

private String inputStreamToString(InputStream in) throws IOException {
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  byte[] buffer = new byte[4096];
  int read = in.read(buffer);
  while (read != -1) {
   bytes.write(buffer, 0, read);
   read = in.read(buffer);
  }
  in.close();
  return bytes.toString();
 }
}

代码示例来源:origin: opensourceBIM/BIMserver

public void setData(InputStream inputStream) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, output);
    setData(output.toByteArray());
    inputStream.close();
  }
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testToInputStreamWithReset() throws IOException {
  //Make sure reset() do not destroy InputStream returned from toInputStream()
  final ByteArrayOutputStream baout = new ByteArrayOutputStream();
  final java.io.ByteArrayOutputStream ref = new java.io.ByteArrayOutputStream();
  //Write 8224 bytes
  writeData(baout, ref, 32);
  for(int i=0;i<128;i++) {
    writeData(baout, ref, 64);
  }
  //Get data before reset
  final InputStream in = baout.toInputStream();
  byte refData[] = ref.toByteArray();
  //Reset and write some new data
  baout.reset();
  ref.reset();
  writeData(baout, ref, new int[] { 2, 4, 8, 16 });
  //Check original data
  byte baoutData[] = IOUtils.toByteArray(in);
  assertEquals(8224, baoutData.length);
  checkByteArrays(refData, baoutData);
  //Check new data written after reset
  baoutData = IOUtils.toByteArray(baout.toInputStream());
  refData = ref.toByteArray();
  assertEquals(30, baoutData.length);
  checkByteArrays(refData, baoutData);
  baout.close();
  in.close();
}

代码示例来源:origin: apache/incubator-gobblin

/**
 * Encrypt a test string with a symmetric key and check that it can be decrypted
 * @throws IOException
 * @throws PGPException
 */
@Test
public void encryptSym() throws IOException, PGPException {
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 OutputStream os = GPGFileEncryptor.encryptFile(baos, PASSWORD, "DES");
 os.write(EXPECTED_FILE_CONTENT_BYTES);
 os.close();
 baos.close();
 byte[] encryptedBytes = baos.toByteArray();
 try (InputStream is = GPGFileDecryptor.decryptFile(new ByteArrayInputStream(encryptedBytes), "test")) {
  byte[] decryptedBytes = IOUtils.toByteArray(is);
  Assert.assertNotEquals(EXPECTED_FILE_CONTENT_BYTES, encryptedBytes);
  Assert.assertEquals(EXPECTED_FILE_CONTENT_BYTES, decryptedBytes);
 }
}

代码示例来源:origin: apache/flume

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
 IOUtils.copy(inputStream, outputStream);
 LOG.debug("Building an Event with stream of size -- {}", outputStream.size());
 Event event = EventBuilder.withBody(outputStream.toByteArray(), headers);
 event.setHeaders(headers);
 List<Event> eventList = new ArrayList<Event>();
 return eventList;
} finally {
 outputStream.close();
 inputStream.close();

代码示例来源:origin: commons-io/commons-io

@Test(expected = NullPointerException.class)
public void testCopy_readerToWriter_nullIn() throws Exception {
  final ByteArrayOutputStream baout = new ByteArrayOutputStream();
  final OutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true);
  final Writer writer = new OutputStreamWriter(out, "US-ASCII");
  IOUtils.copy((Reader) null, writer);
}

代码示例来源:origin: commons-io/commons-io

final ByteArrayOutputStream baout = new ByteArrayOutputStream(32);
final java.io.ByteArrayOutputStream ref = new java.io.ByteArrayOutputStream();
baout.reset();
ref.reset();
baout.reset();
written = baout.write(new ByteArrayInputStream(ref.toByteArray()));
assertEquals(155, written);
checkStreams(baout, ref);
final ByteArrayOutputStream baout1 = new ByteArrayOutputStream(32);
ref.writeTo(baout1);
final java.io.ByteArrayOutputStream ref1 = new java.io.ByteArrayOutputStream();
baout.writeTo(ref1);
checkStreams(baout1, ref1);
final String baoutString = baout.toString("ASCII");
final String refString = ref.toString("ASCII");
assertEquals("ASCII decoded String must be equal", refString, baoutString);
final ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
final ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
assertSame(baos1.toByteArray(), baos2.toByteArray());
baos1.close();
baos2.close();
baout.close();
baout1.close();

代码示例来源:origin: commons-io/commons-io

@Test
public void testWriteLines_Writer_nullSeparator() throws Exception {
  final Object[] data = new Object[]{"hello", "world"};
  final List<Object> list = Arrays.asList(data);
  final ByteArrayOutputStream baout = new ByteArrayOutputStream();
  @SuppressWarnings("resource") // deliberately not closed
  final YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true);
  final Writer writer = new OutputStreamWriter(baout, "US-ASCII");
  IOUtils.writeLines(list, null, writer);
  out.off();
  writer.flush();
  final String expected = "hello" + IOUtils.LINE_SEPARATOR + "world" + IOUtils.LINE_SEPARATOR;
  final String actual = baout.toString();
  assertEquals(expected, actual);
}

代码示例来源:origin: palantir/atlasdb

@Test
public void testAddDelete() throws Exception {
  final byte[] data = PtBytes.toBytes("streamed");
  final long streamId = txManager.runTaskWithRetry((TransactionTask<Long, Exception>) t -> {
    Sha256Hash hash = Sha256Hash.computeHash(data);
    byte[] reference = "ref".getBytes();
    return defaultStore.getByHashOrStoreStreamAndMarkAsUsed(t, hash, new ByteArrayInputStream(data), reference);
  });
  txManager.runTaskWithRetry((TransactionTask<Void, Exception>) t -> {
    Optional<InputStream> inputStream = defaultStore.loadSingleStream(t, streamId);
    assertTrue(inputStream.isPresent());
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    outputStream.write(inputStream.get());
    assertArrayEquals(data, outputStream.toByteArray());
    return null;
  });
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testWriteLines_Writer_nullData() throws Exception {
  final ByteArrayOutputStream baout = new ByteArrayOutputStream();
  @SuppressWarnings("resource") // deliberately not closed
  final YellOnFlushAndCloseOutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true);
  final Writer writer = new OutputStreamWriter(baout, "US-ASCII");
  IOUtils.writeLines(null, "*", writer);
  out.off();
  writer.flush();
  assertEquals("Sizes differ", 0, baout.size());
}

代码示例来源:origin: commons-io/commons-io

@SuppressWarnings("deprecation")
@Test(expected = NullPointerException.class)
public void testCopy_readerToOutputStream_nullIn() throws Exception { // deliberately testing deprecated method
  final ByteArrayOutputStream baout = new ByteArrayOutputStream();
  final OutputStream out = new YellOnFlushAndCloseOutputStream(baout, true, true);
  IOUtils.copy((Reader) null, out);
}

相关文章