Java Code Examples for java.io.ByteArrayOutputStream#toByteArray()

The following examples show how to use java.io.ByteArrayOutputStream#toByteArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EncodingConstructor.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    String s = "xyzzy";
    int n = s.length();
    try (PrintStream ps = new PrintStream(bo, false, "UTF-8")) {
        ps.print(s);
    }
    byte[] ba = bo.toByteArray();
    if (ba.length != n)
        throw new Exception("Length mismatch: " + n + " " + ba.length);
    for (int i = 0; i < n; i++) {
        if (ba[i] != (byte)s.charAt(i))
            throw new Exception("Content mismatch: "
                                + i + " "
                                + Integer.toString(ba[i]) + " "
                                + Integer.toString(s.charAt(i)));
    }
}
 
Example 2
Source File: Test.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static void serial() throws IOException, MalformedURLException {

        header("Serialization");

        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        URL u = new URL("http://java.sun.com/jdk/1.4?release#beta");
        oo.writeObject(u);
        oo.close();

        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        try {
            Object o = oi.readObject();
            u.equals(o);
        } catch (ClassNotFoundException x) {
            x.printStackTrace();
            throw new RuntimeException(x.toString());
        }

    }
 
Example 3
Source File: UtilAll.java    From rocketmq-read with Apache License 2.0 6 votes vote down vote up
/**
 * 压缩
 * @param src ;
 * @param level ;
 * @return ;
 * @throws IOException ;
 */
public static byte[] compress(final byte[] src, final int level) throws IOException {
    byte[] result = src;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
    java.util.zip.Deflater defeater = new java.util.zip.Deflater(level);
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, defeater);
    try {
        deflaterOutputStream.write(src);
        deflaterOutputStream.finish();
        deflaterOutputStream.close();
        result = byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
        defeater.end();
        throw e;
    } finally {
        try {
            byteArrayOutputStream.close();
        } catch (IOException ignored) {
        }

        defeater.end();
    }

    return result;
}
 
Example 4
Source File: GZIPUtils.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
/**
 * GZIP解压缩
 *
 * @param bytes
 * @return
 */
public static byte[] uncompress(byte[] bytes) {
    if (bytes == null || bytes.length == 0) {
        return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    try {
        GZIPInputStream ungzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = ungzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return out.toByteArray();
}
 
Example 5
Source File: Script.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/** Returns the serialized program as a newly created byte array. */
public byte[] getProgram() {
    try {
        // Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch.
        if (program != null)
            return Arrays.copyOf(program, program.length);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        for (ScriptChunk chunk : chunks) {
            chunk.write(bos);
        }
        program = bos.toByteArray();
        return program;
    } catch (IOException e) {
        throw new RuntimeException(e);  // Cannot happen.
    }
}
 
Example 6
Source File: TestCompressionInputOutputStreams.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataLargerThanBufferWhileFlushing() throws IOException {
    final String str = "The quick brown fox jumps over the lazy dog\r\n\n\n\r";
    final byte[] data = str.getBytes("UTF-8");

    final StringBuilder sb = new StringBuilder();
    final byte[] data1024;

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final CompressionOutputStream cos = new CompressionOutputStream(baos, 8192);
    for (int i = 0; i < 1024; i++) {
        cos.write(data);
        cos.flush();
        sb.append(str);
    }
    cos.close();
    data1024 = sb.toString().getBytes("UTF-8");

    final byte[] compressedBytes = baos.toByteArray();
    final CompressionInputStream cis = new CompressionInputStream(new ByteArrayInputStream(compressedBytes));
    final byte[] decompressed = readFully(cis);

    assertTrue(Arrays.equals(data1024, decompressed));
}
 
Example 7
Source File: PoiPublicUtil.java    From jeasypoi with Apache License 2.0 6 votes vote down vote up
/**
 * 返回流和图片类型
 * 
 * @Author JueYue
 * @date 2013-11-20
 * @param entity
 * @return (byte[]) isAndType[0],(Integer)isAndType[1]
 * @throws Exception
 */
public static Object[] getIsAndType(WordImageEntity entity) throws Exception {
	Object[] result = new Object[2];
	String type;
	if (entity.getType().equals(WordImageEntity.URL)) {
		ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
		BufferedImage bufferImg;
		String path = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + entity.getUrl();
		path = path.replace("WEB-INF/classes/", "");
		path = path.replace("file:/", "");
		bufferImg = ImageIO.read(new File(path));
		ImageIO.write(bufferImg, entity.getUrl().substring(entity.getUrl().indexOf(".") + 1, entity.getUrl().length()), byteArrayOut);
		result[0] = byteArrayOut.toByteArray();
		type = entity.getUrl().split("/.")[entity.getUrl().split("/.").length - 1];
	} else {
		result[0] = entity.getData();
		type = PoiPublicUtil.getFileExtendName(entity.getData());
	}
	result[1] = getImageType(type);
	return result;
}
 
Example 8
Source File: GzipUtil.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
/**
 * GZIP 压缩字符串
 * 
 * @param String str
 * @param String charsetName
 * @return byte[]
 * @throws IOException
 */
public static byte[] compressString2byte(String str, String charsetName) throws IOException {
    if (str == null || str.trim().length() == 0) {
        return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    gzip.write(str.getBytes(charsetName));
    gzip.close();
    return out.toByteArray();
}
 
Example 9
Source File: LambdaClassLoaderSerialization.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private byte[] serialize(Object o) {
    ByteArrayOutputStream baos;
    try (
        ObjectOutputStream oos =
            new ObjectOutputStream(baos = new ByteArrayOutputStream())
    ) {
        oos.writeObject(o);
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
    return baos.toByteArray();
}
 
Example 10
Source File: SetLoopType.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
        double ii = i / 1024.0;
        ii = ii * ii;
        testarray[i] = (float)Math.sin(10*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI);
        testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    buffer = new ModelByteBuffer(test_byte_array);

    byte[] test_byte_array2 = new byte[testarray.length*3];
    buffer24 = new ModelByteBuffer(test_byte_array2);
    test_byte_array_8ext = new byte[testarray.length];
    byte[] test_byte_array_8_16 = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format24).toByteArray(testarray, test_byte_array2);
    int ix = 0;
    int x = 0;
    for (int i = 0; i < test_byte_array_8ext.length; i++) {
        test_byte_array_8ext[i] = test_byte_array2[ix++];
        test_byte_array_8_16[x++] = test_byte_array2[ix++];
        test_byte_array_8_16[x++] = test_byte_array2[ix++];
    }
    buffer16_8 = new ModelByteBuffer(test_byte_array_8_16);
    buffer8 = new ModelByteBuffer(test_byte_array_8ext);

    AudioInputStream ais = new AudioInputStream(buffer.getInputStream(), format, testarray.length);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    AudioSystem.write(ais, AudioFileFormat.Type.WAVE, baos);
    buffer_wave = new ModelByteBuffer(baos.toByteArray());
}
 
Example 11
Source File: DefaultViewStorage.java    From protect with MIT License 5 votes vote down vote up
public byte[] getBytes(View view) {
	try {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(4);
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(view);
		return baos.toByteArray();
	} catch (Exception e) {
		return null;
	}
}
 
Example 12
Source File: HistoricVariableInstanceDataResource.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Indicates the variable instance was found and the requested variable data is returned."),
    @ApiResponse(code = 404, message = "Indicates the requested variable instance was not found or the variable instance doesn’t have a variable with the given name or the variable doesn’t have a binary stream available. Status message provides additional information.")})
@ApiOperation(value = "Get the binary data for a historic task instance variable", tags = {"History"}, nickname = "getHistoricInstanceVariableData",
notes = "The response body contains the binary value of the variable. When the variable is of type binary, the content-type of the response is set to application/octet-stream, regardless of the content of the variable or the request accept-type header. In case of serializable, application/x-java-serialized-object is used as content-type.")
@RequestMapping(value = "/history/historic-variable-instances/{varInstanceId}/data", method = RequestMethod.GET)
public @ResponseBody
byte[] getVariableData(@ApiParam(name="varInstanceId") @PathVariable("varInstanceId") String varInstanceId, HttpServletRequest request, HttpServletResponse response) {

  try {
    byte[] result = null;
    RestVariable variable = getVariableFromRequest(true, varInstanceId, request);
    if (RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variable.getType())) {
      result = (byte[]) variable.getValue();
      response.setContentType("application/octet-stream");

    } else if (RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variable.getType())) {
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      ObjectOutputStream outputStream = new ObjectOutputStream(buffer);
      outputStream.writeObject(variable.getValue());
      outputStream.close();
      result = buffer.toByteArray();
      response.setContentType("application/x-java-serialized-object");

    } else {
      throw new ActivitiObjectNotFoundException("The variable does not have a binary data stream.", null);
    }
    return result;

  } catch (IOException ioe) {
    // Re-throw IOException
    throw new ActivitiException("Unexpected exception getting variable data", ioe);
  }
}
 
Example 13
Source File: HttpProxyCacheTest.java    From AndriodVideoCache with Apache License 2.0 5 votes vote down vote up
private Response processRequest(HttpProxyCache proxyCache, String httpRequest) throws ProxyCacheException, IOException {
    GetRequest request = new GetRequest(httpRequest);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Socket socket = mock(Socket.class);
    when(socket.getOutputStream()).thenReturn(out);
    proxyCache.processRequest(request, socket);
    return new Response(out.toByteArray());
}
 
Example 14
Source File: CameraUtils.java    From wallpaper with GNU General Public License v2.0 5 votes vote down vote up
public static byte[] getBytes(InputStream is) throws IOException {
    ByteArrayOutputStream outstream = new ByteArrayOutputStream();
    //把所有的变量收集到一起,然后一次性把数据发送出去
    byte[] buffer = new byte[1024]; // 用数据装
    int len = 0;
    while ((len = is.read(buffer)) != -1) {
        outstream.write(buffer, 0, len);
    }
    outstream.close();

    return outstream.toByteArray();
}
 
Example 15
Source File: TCKLocalTimeSerialization.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_serialization_format_h() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (DataOutputStream dos = new DataOutputStream(baos) ) {
        dos.writeByte(4);
        dos.writeByte(-1 - 22);
    }
    byte[] bytes = baos.toByteArray();
    assertSerializedBySer(LocalTime.of(22, 0), bytes);
}
 
Example 16
Source File: CFDv3.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
byte[] getOriginalBytes() throws Exception {
    JAXBSource in = new JAXBSource(context, document);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Result out = new StreamResult(baos);
    TransformerFactory factory = tf;
    if (factory == null) {
        factory = TransformerFactory.newInstance();
        factory.setURIResolver(new URIResolverImpl());
    }
    Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
    transformer.transform(in, out);
    return baos.toByteArray();
}
 
Example 17
Source File: WrapToken.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public int encode(byte[] outToken, int offset)
    throws IOException, GSSException  {

    // Token header is small
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    super.encode(bos);
    byte[] header = bos.toByteArray();
    System.arraycopy(header, 0, outToken, offset, header.length);
    offset += header.length;

    // debug("WrapToken.encode: Writing data: [");
    if (!privacy) {

        // debug(getHexBytes(confounder, confounder.length));
        System.arraycopy(confounder, 0, outToken, offset,
                         confounder.length);
        offset += confounder.length;

        // debug(" " + getHexBytes(dataBytes, dataOffset, dataLen));
        System.arraycopy(dataBytes, dataOffset, outToken, offset,
                         dataLen);
        offset += dataLen;

        // debug(" " + getHexBytes(padding, padding.length));
        System.arraycopy(padding, 0, outToken, offset, padding.length);

    } else {

        cipherHelper.encryptData(this, confounder, dataBytes,
            dataOffset, dataLen, padding, outToken, offset);

        // debug(getHexBytes(outToken, offset, dataSize));
    }

    // debug("]\n");

    // %%% assume that plaintext length == ciphertext len
    return (header.length + confounder.length + dataLen + padding.length);

}
 
Example 18
Source File: SimpleTestGO2O.java    From sofa-hessian with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testIntegers() throws IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    Hessian2Output hout = new Hessian2Output(bout);
    hout.setSerializerFactory(new GenericSerializerFactory());

    //single byte
    hout.writeObject(dg.generateInt_0());
    hout.writeObject(dg.generateInt_1());
    hout.writeObject(dg.generateInt_47());
    hout.writeObject(dg.generateInt_m16());

    //two bytes
    hout.writeObject(dg.generateInt_0x30());
    hout.writeObject(dg.generateInt_0x7ff());
    hout.writeObject(dg.generateInt_m17());
    hout.writeObject(dg.generateInt_m0x800());

    //three bytes
    hout.writeObject(dg.generateInt_0x800());
    hout.writeObject(dg.generateInt_0x3ffff());
    hout.writeObject(dg.generateInt_m0x801());
    hout.writeObject(dg.generateInt_m0x40000());

    //five bytes
    hout.writeObject(dg.generateInt_0x40000());
    hout.writeObject(dg.generateInt_0x7fffffff());
    hout.writeObject(dg.generateInt_m0x40001());
    hout.writeObject(dg.generateInt_m0x80000000());

    hout.close();

    byte[] body = bout.toByteArray();
    ByteArrayInputStream bin = new ByteArrayInputStream(body, 0, body.length);
    Hessian2Input hin = new Hessian2Input(bin);
    hin.setSerializerFactory(new SerializerFactory());

    //single byte
    assertEquals(dg.generateInt_0(), hin.readObject());
    assertEquals(dg.generateInt_1(), hin.readObject());
    assertEquals(dg.generateInt_47(), hin.readObject());
    assertEquals(dg.generateInt_m16(), hin.readObject());

    //two bytes
    assertEquals(dg.generateInt_0x30(), hin.readObject());
    assertEquals(dg.generateInt_0x7ff(), hin.readObject());
    assertEquals(dg.generateInt_m17(), hin.readObject());
    assertEquals(dg.generateInt_m0x800(), hin.readObject());

    //three bytes
    assertEquals(dg.generateInt_0x800(), hin.readObject());
    assertEquals(dg.generateInt_0x3ffff(), hin.readObject());
    assertEquals(dg.generateInt_m0x801(), hin.readObject());
    assertEquals(dg.generateInt_m0x40000(), hin.readObject());

    //five bytes
    assertEquals(dg.generateInt_0x40000(), hin.readObject());
    assertEquals(dg.generateInt_0x7fffffff(), hin.readObject());
    assertEquals(dg.generateInt_m0x40001(), hin.readObject());
    assertEquals(dg.generateInt_m0x80000000(), hin.readObject());

    hin.close();
}
 
Example 19
Source File: NativeObfuscator.java    From native-obfuscator with GNU General Public License v3.0 4 votes vote down vote up
private String writeStreamToString(InputStream stream) throws IOException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	transfer(stream, baos);
	return new String(baos.toByteArray(), StandardCharsets.UTF_8);
}
 
Example 20
Source File: CheckLogging.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Check serverCallLog output
 */
private static void checkServerCallLog() throws Exception {
    ByteArrayOutputStream serverCallLog = new ByteArrayOutputStream();
    RemoteServer.setLog(serverCallLog);
    Naming.list(LOCATION);
    verifyLog(serverCallLog, "list");

    serverCallLog.reset();
    RemoteServer.setLog(null);
    PrintStream callStream = RemoteServer.getLog();
    if (callStream != null) {
        TestLibrary.bomb("call stream not null after calling " +
                         "setLog(null)");
    } else {
        System.err.println("call stream should be null and it is");
    }
    Naming.list(LOCATION);

    if (usingOld) {
        if (serverCallLog.toString().indexOf("UnicastServerRef") >= 0) {
            TestLibrary.bomb("server call logging not turned off");
        }
    } else if (serverCallLog.toByteArray().length != 0) {
        TestLibrary.bomb("call log contains output but it " +
                         "should be empty");
    }

    serverCallLog.reset();
    RemoteServer.setLog(serverCallLog);
    try {
        // generates a notbound exception
        Naming.lookup(LOCATION + "notthere");
    } catch (Exception e) {
    }
    verifyLog(serverCallLog, "exception");

    serverCallLog.reset();
    RemoteServer.setLog(serverCallLog);
    callStream = RemoteServer.getLog();
    callStream.println("bingo, this is a getLog test");
    verifyLog(serverCallLog, "bingo");
}