当前位置: 首页>>代码示例>>Java>>正文


Java ByteArrayOutputStream类代码示例

本文整理汇总了Java中org.apache.commons.io.output.ByteArrayOutputStream的典型用法代码示例。如果您正苦于以下问题:Java ByteArrayOutputStream类的具体用法?Java ByteArrayOutputStream怎么用?Java ByteArrayOutputStream使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ByteArrayOutputStream类属于org.apache.commons.io.output包,在下文中一共展示了ByteArrayOutputStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: zipEntries

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
private ByteArrayOutputStream zipEntries(List<Pair<String, byte[]>> entryList) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(8192);
    try (ZipOutputStream jar = new ZipOutputStream(buffer)) {
        jar.setMethod(ZipOutputStream.STORED);
        final CRC32 crc = new CRC32();
        for (Pair<String, byte[]> entry : entryList) {
            byte[] bytes = entry.second;
            final ZipEntry newEntry = new ZipEntry(entry.first);
            newEntry.setMethod(ZipEntry.STORED); // chose STORED method
            crc.reset();
            crc.update(entry.second);
            newEntry.setCrc(crc.getValue());
            newEntry.setSize(bytes.length);
            writeEntryToJar(newEntry, bytes, jar);
        }
        jar.flush();
    }
    return buffer;
}
 
开发者ID:yrom,项目名称:shrinker,代码行数:20,代码来源:JarProcessor.java

示例2: proceed

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
@Override
public void proceed() {
    try {
        List<Pair<String, byte[]>> entryList = readZipEntries(src)
                .parallelStream()
                .map(this::transformClassBlob)
                .collect(Collectors.toList());
        if (entryList.isEmpty()) return;
        try (OutputStream fileOut = Files.newOutputStream(dst)) {
            ByteArrayOutputStream buffer = zipEntries(entryList);
            buffer.writeTo(fileOut);
        }
    } catch (IOException e) {
        throw new RuntimeException("Reading jar entries failure", e);
    }
}
 
开发者ID:yrom,项目名称:shrinker,代码行数:17,代码来源:JarProcessor.java

示例3: getResponseEntity

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
private String getResponseEntity(HttpResponse result) throws IOException {
    HttpEntity entity = result.getEntity();
    if (entity == null) {
        log.debug("Null response entity");
        return null;
    }

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        entity.writeTo(bos);
        byte[] bytes = bos.toByteArray();
        if (bytes == null) {
            bytes = "null".getBytes();
        }
        String response = new String(bytes);
        log.debug("Response with code " + result + ": " + response);
        return response;
    } finally {
        InputStream content = entity.getContent();
        if (content != null) {
            content.close();
        }
    }
}
 
开发者ID:Blazemeter,项目名称:jmeter-bzm-plugins,代码行数:25,代码来源:HttpUtils.java

示例4: main

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
    String cmd = "/tmp/test.sh";
    CommandLine cmdLine = CommandLine.parse("/bin/bash " + cmd);

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout, stderr);

    psh.setStopTimeout(TIMEOUT_FIVE_MINUTES);

    ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT_TEN_MINUTES); // timeout in milliseconds

    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setStreamHandler(psh);
    executor.setWatchdog(watchdog);

    int exitValue = executor.execute(cmdLine, Collections.emptyMap());
    System.out.println(exitValue);
}
 
开发者ID:kinow,项目名称:commons-sandbox,代码行数:21,代码来源:Tests.java

示例5: render

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
/**
 * Renders an input file (XML or XSL-FO) into a PDF file. It uses the JAXP
 * transformer given to optionally transform the input document to XSL-FO.
 * The transformer may be an identity transformer in which case the input
 * must already be XSL-FO. The PDF is written to a byte array that is
 * returned as the method's result.
 * @param src Input XML or XSL-FO
 * @param transformer Transformer to use for optional transformation
 * @param response HTTP response object
 * @throws FOPException If an error occurs during the rendering of the
 * XSL-FO
 * @throws TransformerException If an error occurs during XSL
 * transformation
 * @throws IOException In case of an I/O problem
 */
public void render(Source src, Transformer transformer, HttpServletResponse response, String realpath)
            throws FOPException, TransformerException, IOException {

    FOUserAgent foUserAgent = getFOUserAgent(realpath);

    //Setup output
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    //Setup FOP
    fopFactory.setBaseURL(realpath);
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);


    //Make sure the XSL transformation's result is piped through to FOP
    Result res = new SAXResult(fop.getDefaultHandler());

    //Start the transformation and rendering process
    transformer.transform(src, res);

    //Return the result
    sendPDF(out.toByteArray(), response);
}
 
开发者ID:malglam,项目名称:Lester,代码行数:38,代码来源:CreatePDF.java

示例6: getNext

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
@Override
public void getNext(CAS aCAS)
        throws IOException, CollectionException
{
    // nextTarEntry cannot be null here!
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int size = IOUtils.copy(tarArchiveInputStream, buffer);

    String entryName = nextTarEntry.getName();
    getLogger().debug("Loaded " + size + " bytes from " + entryName);

    // and move forward
    fastForwardToNextValidEntry();

    // and now create JCas
    InputStream inputStream = new ByteArrayInputStream(buffer.toByteArray());
    try {
        XmiCasDeserializer.deserialize(inputStream, aCAS, lenient);
    }
    catch (SAXException e) {
        throw new IOException(e);
    }
}
 
开发者ID:UKPLab,项目名称:argument-reasoning-comprehension-task,代码行数:24,代码来源:CompressedXmiReader.java

示例7: testSecureCopyFile

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
@Test
public void testSecureCopyFile() throws JSchException, IOException {
    final JschBuilder mockJschBuilder = mock(JschBuilder.class);
    final JSch mockJsch = mock(JSch.class);
    final Session mockSession = mock(Session.class);
    final ChannelExec mockChannelExec = mock(ChannelExec.class);
    final byte [] bytes = {0};
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    when(mockChannelExec.getInputStream()).thenReturn(new TestInputStream());
    when(mockChannelExec.getOutputStream()).thenReturn(out);
    when(mockSession.openChannel(eq("exec"))).thenReturn(mockChannelExec);
    when(mockJsch.getSession(anyString(), anyString(), anyInt())).thenReturn(mockSession);
    when(mockJschBuilder.build()).thenReturn(mockJsch);
    when(Config.mockSshConfig.getJschBuilder()).thenReturn(mockJschBuilder);
    when(Config.mockRemoteCommandExecutorService.executeCommand(any(RemoteExecCommand.class))).thenReturn(mock(RemoteCommandReturnInfo.class));
    final String source = BinaryDistributionControlServiceImplTest.class.getClassLoader().getResource("binarydistribution/copy.txt").getPath();
    binaryDistributionControlService.secureCopyFile("someHost", source, "./build/tmp");
    verify(Config.mockSshConfig).getJschBuilder();
    assertEquals("C0644 12 copy.txt\nsome content\0", out.toString(StandardCharsets.UTF_8));
}
 
开发者ID:cerner,项目名称:jwala,代码行数:21,代码来源:BinaryDistributionControlServiceImplTest.java

示例8: testDownloadDataBlob

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
@Test
public void testDownloadDataBlob() throws Exception {
	final URL jarLocation = getBlobFile();
	InputStream openStream = null;
	try {
		// Get the JAR input
		openStream = jarLocation.openStream();

		// Proceed to the test
		resource.prepareData(openStream, 1);
		final StreamingOutput downloadLobFile = resource.downloadLobFile();
		final ByteArrayOutputStream output = new ByteArrayOutputStream();
		downloadLobFile.write(output);
		org.junit.Assert.assertTrue(output.toByteArray().length > 3000000);
	} finally {
		IOUtils.closeQuietly(openStream);
	}
}
 
开发者ID:ligoj,项目名称:bootstrap,代码行数:19,代码来源:JpaBenchResourceTest.java

示例9: copy

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
/**
 * Clone  a Protostuff object
 *
 * @param t the protobuf message to copy
 * @return a deep copy of {@code t}
 */
public static <T extends Message<T>> T copy(T t) {
  try {
    Schema<T> schema = t.cachedSchema();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GraphIOUtil.writeDelimitedTo(new DataOutputStream(out), t, schema);
    // TODO: avoid array copy
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    T newMessage = schema.newMessage();
    GraphIOUtil.mergeDelimitedFrom(in, newMessage, schema);
    return newMessage;
  } catch (IOException e) {
    throw UserException.dataReadError(e)
      .message("Failure decoding object, please ensure that you ran dremio-admin upgrade on Dremio.")
      .build(logger);
  }
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:23,代码来源:ProtostuffUtil.java

示例10: encrypt

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
@Override
byte[] encrypt(byte[] key, byte[] data) {
  try {
    SecretKeySpec keySpec = new SecretKeySpec(key, AES);
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    byte[] ciphertext = cipher.doFinal(data);

    // Write out the metadata.
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    DataOutput out = new DataOutputStream(stream);

    byte[] params = cipher.getParameters().getEncoded();
    WritableUtils.writeVInt(out, params.length);
    out.write(params);

    // Write the original ciphertext and return the new ciphertext.
    out.write(ciphertext);
    return stream.toByteArray();
  } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException e) {
    throw new EncryptionException(e);
  }
}
 
开发者ID:mit-ll,项目名称:PACE,代码行数:23,代码来源:AESValueEncryptor.java

示例11: getStatusHistory

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
@Test
public void getStatusHistory() throws Exception {
	final int subscription = getSubscription("MDA");
	final StreamingOutput csv = (StreamingOutput) resource.getStatusHistory(subscription, "file1").getEntity();
	final ByteArrayOutputStream out = new ByteArrayOutputStream();
	csv.write(out);
	final BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()), "cp1252"));
	final String header = inputStreamReader.readLine();
	Assert.assertEquals("issueid;key;author;from;to;fromText;toText;date;dateTimestamp", header);
	String lastLine = inputStreamReader.readLine();
	Assert.assertEquals("11432;MDA-1;fdaugan;;1;;OPEN;2009/03/23 15:26:43;1237818403000", lastLine);
	lastLine = inputStreamReader.readLine();
	Assert.assertEquals("11437;MDA-4;xsintive;;1;;OPEN;2009/03/23 16:23:31;1237821811000", lastLine);
	lastLine = inputStreamReader.readLine();
	lastLine = inputStreamReader.readLine();
	lastLine = inputStreamReader.readLine();
	lastLine = inputStreamReader.readLine();
	Assert.assertEquals("11535;MDA-8;challer;;1;;OPEN;2009/04/01 14:20:29;1238588429000", lastLine);
	lastLine = inputStreamReader.readLine();
	lastLine = inputStreamReader.readLine();
	lastLine = inputStreamReader.readLine();
	Assert.assertEquals("11535;MDA-8;fdaugan;1;10024;OPEN;ASSIGNED;2009/04/09 09:45:16;1239263116000", lastLine);
	lastLine = inputStreamReader.readLine();
	Assert.assertEquals("11535;MDA-8;fdaugan;10024;3;ASSIGNED;IN PROGRESS;2009/04/09 09:45:30;1239263130000", lastLine);
}
 
开发者ID:ligoj,项目名称:plugin-bt-jira,代码行数:26,代码来源:JiraExportPluginResourceTest.java

示例12: testReadByte

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
@Test
public void testReadByte() throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);
    OptimizedInterceptedFileOutputStream outStream = new OptimizedInterceptedFileOutputStream(stream);
    outStream.write(new AugmentedString(1, ',', 1.5, ',', "foo", '\n'));
    outStream.close();

    OptimizedInterceptedFileInputStream inStream =
            new OptimizedInterceptedFileInputStream(new ByteArrayInputStream(stream.toByteArray()));

    ByteBuffer buffer = ByteBuffer.allocate(10);
    for(int i = 0; i < "1,1.5,foo\n".length(); i++)
        buffer.put((byte)inStream.read());

    assert(new String(buffer.array()).equals("1,1.5,foo\n"));
    assert(inStream.read() == -1);
}
 
开发者ID:uwdb,项目名称:pipegen,代码行数:18,代码来源:InterceptedFileInputStreamTests.java

示例13: convertBufferToBytes

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
/**
 * Converts a BufferedInputStream to a byte array
 *
 * @param inputStream
 * @param bufferLength
 * @return
 * @throws IOException
 */
private byte[] convertBufferToBytes(BufferedInputStream inputStream, int bufferLength) throws IOException {
    if (inputStream == null)
        return null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[bufferLength];
    int x = inputStream.read(buffer, 0, bufferLength);
    Log.i("GraphServiceController", "bytes read from picture input stream " + String.valueOf(x));

    int n = 0;
    try {
        while ((n = inputStream.read(buffer, 0, bufferLength)) >= 0) {
            outputStream.write(buffer, 0, n);
        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    outputStream.close();
    return outputStream.toByteArray();
}
 
开发者ID:microsoftgraph,项目名称:android-java-connect-sample,代码行数:30,代码来源:GraphServiceController.java

示例14: send

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
public void send(COL_ONEM2M event) throws Exception {
	EncoderFactory avroEncoderFactory = EncoderFactory.get();
	SpecificDatumWriter<COL_ONEM2M> avroEventWriter = new SpecificDatumWriter<COL_ONEM2M>(COL_ONEM2M.SCHEMA$);
	
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	BinaryEncoder binaryEncoder = avroEncoderFactory.binaryEncoder(stream,null);

	try {
		avroEventWriter.write(event, binaryEncoder);
		binaryEncoder.flush();
	} catch (IOException e) {
		e.printStackTrace();
		throw e;
	}
	IOUtils.closeQuietly(stream);

	KeyedMessage<String, byte[]> data = new KeyedMessage<String, byte[]>(
			TOPIC, stream.toByteArray());

	producer.send(data);
}
 
开发者ID:iotoasis,项目名称:SDA,代码行数:22,代码来源:AvroOneM2MDataPublish.java

示例15: send

import org.apache.commons.io.output.ByteArrayOutputStream; //导入依赖的package包/类
public void send(COL_RDBMS event) throws Exception {
	EncoderFactory avroEncoderFactory = EncoderFactory.get();
	SpecificDatumWriter<COL_RDBMS> avroEventWriter = new SpecificDatumWriter<COL_RDBMS>(COL_RDBMS.SCHEMA$);
	
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	BinaryEncoder binaryEncoder = avroEncoderFactory.binaryEncoder(stream,null);

	try {
		avroEventWriter.write(event, binaryEncoder);
		binaryEncoder.flush();
	} catch (IOException e) {
		e.printStackTrace();
		throw e;
	}
	IOUtils.closeQuietly(stream);

	KeyedMessage<String, byte[]> data = new KeyedMessage<String, byte[]>(
			TOPIC, stream.toByteArray());

	producer.send(data);
}
 
开发者ID:iotoasis,项目名称:SDA,代码行数:22,代码来源:AvroRdbmsTimeTableWattagePublish.java


注:本文中的org.apache.commons.io.output.ByteArrayOutputStream类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。