类java.io.ByteArrayInputStream源码实例Demo

下面列出了怎么用java.io.ByteArrayInputStream的API类实例代码及写法,或者点击链接到github查看源代码。

public SignRequest createSignRequest(String method, IpPort ipPort, RequestParam requestParam, String url,
    Map<String, String> headers) {
  SignRequest signReq = new SignRequest();
  StringBuilder endpoint = new StringBuilder("https://" + ipPort.getHostOrIp());
  endpoint.append(":" + ipPort.getPort());
  endpoint.append(url);
  try {
    signReq.setEndpoint(new URI(endpoint.toString()));
  } catch (URISyntaxException e) {
    LOGGER.error("set uri failed, uri is {}, message: {}", endpoint.toString(), e.getMessage());
  }
  signReq.setContent((requestParam.getBody() != null && requestParam.getBody().length > 0)
      ? new ByteArrayInputStream(requestParam.getBody())
      : null);
  signReq.setHeaders(headers);
  signReq.setHttpMethod(method);
  signReq.setQueryParams(requestParam.getQueryParamsMap());
  return signReq;
}
 
源代码2 项目: pentaho-metadata   文件: XmiParserIT.java
@Test
public void testMissingDescriptionRef() throws Exception {
  XmiParser parser = new XmiParser();
  Domain domain = parser.parseXmi( getClass().getResourceAsStream( "/missing_ref.xmi" ) );

  String xmi = parser.generateXmi( domain );

  ByteArrayInputStream is = new ByteArrayInputStream( xmi.getBytes() );
  Domain domain2 = parser.parseXmi( is );

  ByteArrayInputStream is2 = new ByteArrayInputStream( parser.generateXmi( domain2 ).getBytes() );
  Domain domain3 = parser.parseXmi( is2 );

  String xml1 = serializeWithOrderedHashmaps( domain2 );
  String xml2 = serializeWithOrderedHashmaps( domain3 );

  // note: this does not verify security objects at this time
  assertEquals( xml1, xml2 );
}
 
源代码3 项目: astor   文件: ComparableObjectSeriesTests.java
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {
    MyComparableObjectSeries s1 = new MyComparableObjectSeries("A");
    s1.add(new Integer(1), "ABC");
    MyComparableObjectSeries s2 = null;
    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(s1);
        out.close();

        ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray()));
        s2 = (MyComparableObjectSeries) in.readObject();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(s1, s2);
}
 
源代码4 项目: uima-uimaj   文件: NewPrimitiveTypesTest.java
public void testBlobSerialization() throws Exception {

    // create FS
    createExampleFS(cas);

    // serialize
    ByteArrayOutputStream fos = new ByteArrayOutputStream();
    Serialization.serializeCAS(cas, fos);

    // reset
    cas.reset();

    // deserialize
    ByteArrayInputStream fis = new ByteArrayInputStream(fos.toByteArray());
    Serialization.deserializeCAS(cas, fis);

    // check values
    validateFSData(cas);
  }
 
源代码5 项目: zap-extensions   文件: WSDLCustomParser.java
private boolean parseWSDLContent(String content, boolean sendMessages) {
    if (content == null || content.trim().length() <= 0) {
        return false;
    } else {
        // WSDL parsing.
        WSDLParser parser = new WSDLParser();
        try {
            InputStream contentI = new ByteArrayInputStream(content.getBytes("UTF-8"));
            Definitions wsdl = parser.parse(contentI);
            contentI.close();
            parseWSDL(wsdl, sendMessages);
            return true;
        } catch (Exception e) {
            LOG.error("There was an error while parsing WSDL content. ", e);
            return false;
        }
    }
}
 
源代码6 项目: sakai   文件: RSA_SHA1.java
private PublicKey getPublicKeyFromPem(String pem) 
throws GeneralSecurityException, IOException {

    InputStream stream = new ByteArrayInputStream(
            pem.getBytes("UTF-8"));

    PEMReader reader = new PEMReader(stream);
    byte[] bytes = reader.getDerBytes(); 	
    PublicKey pubKey;

    if (PEMReader.PUBLIC_X509_MARKER.equals(reader.getBeginMarker())) {
        KeySpec keySpec = new X509EncodedKeySpec(bytes);
        KeyFactory fac = KeyFactory.getInstance("RSA");
        pubKey = fac.generatePublic(keySpec);
    } else if (PEMReader.CERTIFICATE_X509_MARKER.equals(reader.getBeginMarker())) {
        pubKey = getPublicKeyFromDerCert(bytes);
    } else {
        throw new IOException("Invalid PEM fileL: Unknown marker for " + 
                " public key or cert " + reader.getBeginMarker());
    }

    return pubKey;
}
 
源代码7 项目: astor   文件: VectorDataItemTests.java
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {
    VectorDataItem v1 = new VectorDataItem(1.0, 2.0, 3.0, 4.0);
    VectorDataItem v2 = null;
    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(v1);
        out.close();

        ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray()));
        v2 = (VectorDataItem) in.readObject();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(v1, v2);
}
 
源代码8 项目: appcan-android   文件: PEncryption.java
/**
 * 加密解密
 *
 * @param pBuffer 要加密或者 要解密的 字节流
 * @param n       要加密或者 要解密的 字节流的大小
 * @param pKey    加密解密的key
 * @param nKeyLen key 的长度
 * @return 返回加密后或者 解密后的字节流
 */
public static byte[] os_decrypt(byte[] pBuffer, int n, String pKey) {
    // PBytes pBytes = new PBytes(pBuffer);
    ByteArrayInputStream in = new ByteArrayInputStream(pBuffer);
    int[] newInt = new int[in.available()];
    int[] resInt = new int[in.available()];
    int ch;
    int i = 0;
    while ((ch = in.read()) != -1) {
        newInt[i] = ch;
        i++;
    }
    RC4(newInt, n, resInt, pKey);
    byte[] newData = new byte[n];
    for (int k = 0; k < n; k++) {
        newData[k] = (byte) resInt[k];
    }
    return newData;
}
 
源代码9 项目: amazon-kinesis-client   文件: MessageReaderTest.java
private InputStream buildInputStreamOfGoodInput(String[] sequenceNumbers, String[] responseFors) {
    // Just interlace the lines
    StringBuilder stringBuilder = new StringBuilder();
    // This is just a reminder to anyone who changes the arrays
    Assert.assertTrue(responseFors.length == sequenceNumbers.length + 1);
    stringBuilder.append(buildStatusLine(responseFors[0]));
    stringBuilder.append("\n");
    // Also a white space line, which it should be able to handle with out failing.
    stringBuilder.append("    \n");
    // Also a bogus data line, which it should be able to handle with out failing.
    stringBuilder.append("  bogus data  \n");
    for (int i = 0; i < Math.min(sequenceNumbers.length, responseFors.length); i++) {
        stringBuilder.append(buildCheckpointLine(sequenceNumbers[i]));
        stringBuilder.append("\n");
        stringBuilder.append(buildStatusLine(responseFors[i + 1]));
        stringBuilder.append("\n");
    }

    return new ByteArrayInputStream(stringBuilder.toString().getBytes());
}
 
源代码10 项目: dubbox-hystrix   文件: AbstractSerializationTest.java
@Test
public void test_Bool() throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeBool(false);
    objectOutput.flushBuffer();

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);

    assertFalse(deserialize.readBool());

    try {
        deserialize.readBool();
        fail();
    } catch (IOException expected) {
    }
}
 
源代码11 项目: spring-data-examples   文件: GridFsTests.java
@Test
public void shouldStoreAndReadFile() throws IOException {

	byte[] bytes;
	try (InputStream is = new BufferedInputStream(new ClassPathResource("./example-file.txt").getInputStream())) {
		bytes = StreamUtils.copyToByteArray(is);
	}

	// store file
	gridFsOperations.store(new ByteArrayInputStream(bytes), "example-file.txt");

	GridFsResource resource = gridFsOperations.getResource("example-file.txt");

	byte[] loaded;
	try (InputStream is = resource.getInputStream()) {
		loaded = StreamUtils.copyToByteArray(is);
	}

	assertThat(bytes).isEqualTo(loaded);
}
 
源代码12 项目: brooklyn-server   文件: CatalogScanOsgiTest.java
static void installJavaScanningMoreEntitiesV2(ManagementContext mgmt, Object context) throws FileNotFoundException {
    // scanning bundle functionality added in 0.12.0, relatively new compared to non-osgi scanning
    
    TestResourceUnavailableException.throwIfResourceUnavailable(context.getClass(), OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    TestResourceUnavailableException.throwIfResourceUnavailable(context.getClass(), OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V2_PATH);
    
    CampYamlLiteTest.installWithoutCatalogBom(mgmt, OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    
    BundleMaker bm = new BundleMaker(mgmt);
    File f = Os.newTempFile(context.getClass(), "jar");
    Streams.copy(ResourceUtils.create(context).getResourceFromUrl(OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V2_PATH), new FileOutputStream(f));
    f = bm.copyRemoving(f, MutableSet.of("catalog.bom"));
    f = bm.copyAdding(f, MutableMap.of(new ZipEntry("catalog.bom"),
        new ByteArrayInputStream( Strings.lines(
            "brooklyn.catalog:",
            "  scanJavaAnnotations: true").getBytes() ) ));
    
    ((ManagementContextInternal)mgmt).getOsgiManager().get().install(new FileInputStream(f)).checkNoError();
}
 
源代码13 项目: gemfirexd-oss   文件: HDFSConfigJUnitTest.java
/**
 * Validates if hdfs store conf is getting complety and correctly parsed
 */
public void testHdfsStoreConfFullParsing() {
  String conf = createStoreConf(null, "123");
  this.c.loadCacheXml(new ByteArrayInputStream(conf.getBytes()));
  HDFSStoreImpl store = ((GemFireCacheImpl)this.c).findHDFSStore("store");
  assertEquals("namenode url mismatch.", "url", store.getNameNodeURL());
  assertEquals("home-dir mismatch.", "dir", store.getHomeDir());
  assertEquals("hdfs-client-config-file mismatch.", "client", store.getHDFSClientConfigFile());
  assertEquals("block-cache-size mismatch.", 24.5f, store.getBlockCacheSize());
  
  HDFSCompactionConfig compactConf = store.getHDFSCompactionConfig();
  assertEquals("compaction strategy mismatch.", "size-oriented", compactConf.getCompactionStrategy());
  assertFalse("compaction auto-compact mismatch.", compactConf.getAutoCompaction());
  assertTrue("compaction auto-major-compact mismatch.", compactConf.getAutoMajorCompaction());
  assertEquals("compaction max-input-file-size mismatch.", 123, compactConf.getMaxInputFileSizeMB());
  assertEquals("compaction min-input-file-count.", 9, compactConf.getMinInputFileCount());
  assertEquals("compaction max-input-file-count.", 1234, compactConf.getMaxInputFileCount());
  assertEquals("compaction max-concurrency", 23, compactConf.getMaxThreads());
  assertEquals("compaction max-major-concurrency", 27, compactConf.getMajorCompactionMaxThreads());
  assertEquals("compaction major-interval", 781, compactConf.getMajorCompactionIntervalMins());
  assertEquals("compaction major-interval", 711, compactConf.getOldFilesCleanupIntervalMins());
}
 
源代码14 项目: CodenameOne   文件: SignIn.java
private void showFacebookUser(String token){
    ConnectionRequest req = new ConnectionRequest();
    req.setPost(false);
    req.setUrl("https://graph.facebook.com/v2.3/me");
    req.addArgumentNoEncoding("access_token", token);
    InfiniteProgress ip = new InfiniteProgress();
    Dialog d = ip.showInifiniteBlocking();
    NetworkManager.getInstance().addToQueueAndWait(req);
    byte[] data = req.getResponseData();
    JSONParser parser = new JSONParser();
    Map map = null;
    try {
        map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String name = (String) map.get("name");
    d.dispose();
    Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), "https://graph.facebook.com/v2.3/me/picture?access_token=" + token);
    userForm.show();
}
 
源代码15 项目: olingo-odata4   文件: ClientEntitySetIterator.java
private ResWrap<Entity> nextAtomEntityFromEntitySet(
        final InputStream input, final OutputStream osEntitySet, final String namespaces) {

  final ByteArrayOutputStream entity = new ByteArrayOutputStream();

  ResWrap<Entity> atomEntity = null;

  try {
    if (consume(input, "<entry>", osEntitySet, false) >= 0) {
      entity.write("<entry ".getBytes(Constants.UTF8));
      entity.write(namespaces.getBytes(Constants.UTF8));
      entity.write(">".getBytes(Constants.UTF8));

      if (consume(input, "</entry>", entity, true) >= 0) {
        atomEntity = odataClient.getDeserializer(ContentType.APPLICATION_ATOM_XML).
                toEntity(new ByteArrayInputStream(entity.toByteArray()));
      }
    }
  } catch (Exception e) {
    LOG.error("Error retrieving entities from EntitySet", e);
  }

  return atomEntity;
}
 
源代码16 项目: dubbo-2.6.5   文件: AbstractSerializationTest.java
<T> void assertObjectArray(T[] data, Class<T[]> clazz) throws Exception {
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(data);
    objectOutput.flushBuffer();

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);

    assertArrayEquals(data, clazz.cast(deserialize.readObject()));

    try {
        deserialize.readObject();
        fail();
    } catch (IOException expected) {
    }
}
 
源代码17 项目: dubbox   文件: AbstractSerializationTest.java
@Test
public void test_charArray_withType() throws Exception {
    char[] data = new char[] { 'a', '中', '无' };
    
    ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
    objectOutput.writeObject(data);
    objectOutput.flushBuffer();
    
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            byteArrayOutputStream.toByteArray());
    ObjectInput deserialize = serialization.deserialize(url, byteArrayInputStream);
    
    assertArrayEquals(data, (char[]) deserialize.readObject(char[].class));
    
    try {
        deserialize.readObject(char[].class);
        fail();
    } catch (IOException expected) {
    }
}
 
源代码18 项目: brooklyn-server   文件: BundleMakerTest.java
@Test
public void testCopyRemovingItems() throws Exception {
    tempJar = bundleMaker.copyAdding(emptyJar, ImmutableMap.of(
            new ZipEntry("myfile.txt"), new ByteArrayInputStream("mytext".getBytes()),
            new ZipEntry("myfile2.txt"), new ByteArrayInputStream("mytext2".getBytes())));
    generatedJar = bundleMaker.copyRemoving(tempJar, ImmutableSet.of("myfile.txt"));
    assertJarContents(generatedJar, ImmutableMap.of("myfile2.txt", "mytext2"), false);
}
 
源代码19 项目: spring4-understanding   文件: FileCopyUtils.java
/**
 * Copy the contents of the given byte array to the given output File.
 * @param in the byte array to copy from
 * @param out the file to copy to
 * @throws IOException in case of I/O errors
 */
public static void copy(byte[] in, File out) throws IOException {
	Assert.notNull(in, "No input byte array specified");
	Assert.notNull(out, "No output File specified");
	ByteArrayInputStream inStream = new ByteArrayInputStream(in);
	OutputStream outStream = new BufferedOutputStream(new FileOutputStream(out));
	copy(inStream, outStream);
}
 
源代码20 项目: swagger-inflector   文件: JacksonProcessorTest.java
@Test
public void testConvertXMLContent() throws Exception {
    String input = "<user><id>1</id><name>fehguy</name></user>";

    EntityProcessorFactory.addProcessor(JacksonProcessor.class, MediaType.APPLICATION_XML_TYPE);

    InputStream is = new ByteArrayInputStream(input.getBytes());
    ObjectNode o = (ObjectNode) EntityProcessorFactory.readValue(MediaType.APPLICATION_XML_TYPE, is, JsonNode.class);
    assertEquals(o.getClass(), ObjectNode.class);
    assertEquals(o.get("name").asText(), "fehguy");
}
 
源代码21 项目: govpay   文件: JaxbUtils.java
public static RR toRR(byte[] rr) throws JAXBException, SAXException {
	init();
	Unmarshaller jaxbUnmarshaller = jaxbRrErContext.createUnmarshaller();
	jaxbUnmarshaller.setSchema(RR_ER_schema);
	JAXBElement<RR> root = jaxbUnmarshaller.unmarshal(new StreamSource(new ByteArrayInputStream(rr)), RR.class);
	return root.getValue();
}
 
源代码22 项目: opencps-v2   文件: JRReportTemplate.java
public static JRReportTemplate getJRReportTemplate(String jrxmlTemplate) throws JRException, IOException {

		InputStream isTemplate = new ByteArrayInputStream(jrxmlTemplate.getBytes(StandardCharsets.UTF_8));
		JRReportTemplate reportTemplate = (JRReportTemplate) JasperCompileManager.compileReport(isTemplate);

		if (isTemplate != null) {
			isTemplate.close();
		}

		return reportTemplate;
	}
 
源代码23 项目: native-obfuscator   文件: Serialization.java
private static HashSet<Integer> serDeser(HashSet<Integer> hashSet) throws IOException, ClassNotFoundException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(hashSet);
    oos.flush();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bais);
    HashSet<Integer> result = (HashSet<Integer>)ois.readObject();

    oos.close();
    ois.close();

    return result;
}
 
源代码24 项目: jdk8u_jdk   文件: ByteArrayImageSource.java
protected ImageDecoder getDecoder() {
    InputStream is =
        new BufferedInputStream(new ByteArrayInputStream(imagedata,
                                                         imageoffset,
                                                         imagelength));
    return getDecoder(is);
}
 
源代码25 项目: appengine-pipelines   文件: SerializationUtils.java
public static Object deserialize(byte[] bytes) throws IOException {
  if (bytes.length < 2) {
    throw new IOException("Invalid bytes content");
  }
  InputStream in = new ByteArrayInputStream(bytes);
  if (bytes[0] == 0) {
    in.read(); // consume the marker;
    if (in.read() != ZLIB_COMPRESSION) {
      throw new IOException("Unknown compression type");
    }
    final Inflater inflater =  new Inflater(true);
    in = new InflaterInputStream(in, inflater) {
      @Override public void close() throws IOException {
        try {
          super.close();
        } finally {
          inflater.end();
        }
      }
    };
  }
  try (ObjectInputStream oin = new ObjectInputStream(in)) {
    try {
      return oin.readObject();
    } catch (ClassNotFoundException e) {
      throw new IOException("Exception while deserilaizing.", e);
    }
  }
}
 
源代码26 项目: signer   文件: PDFSigner.java
/**
 * 
 * Faz a leitura do token em LINUX, precisa setar a lib (.SO) e a senha do token.
 */
@SuppressWarnings("restriction")
private KeyStore getKeyStoreToken() {

	try {
		// ATENÇÃO ALTERAR CONFIGURAÇÃO ABAIXO CONFORME O TOKEN USADO

		// Para TOKEN Branco a linha abaixo
		// String pkcs11LibraryPath =
		// "/usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so";

		// Para TOKEN Azul a linha abaixo
		String pkcs11LibraryPath = "/usr/lib/libeToken.so";

		StringBuilder buf = new StringBuilder();
		buf.append("library = ").append(pkcs11LibraryPath).append("\nname = Provedor\n");
		Provider p = new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(buf.toString().getBytes()));
		Security.addProvider(p);
		// ATENÇÃO ALTERAR "SENHA" ABAIXO
		Builder builder = KeyStore.Builder.newInstance("PKCS11", p,	new KeyStore.PasswordProtection("senha".toCharArray()));
		KeyStore ks;
		ks = builder.getKeyStore();

		return ks;

	} catch (Exception e1) {
		e1.printStackTrace();
		return null;
	} finally {
	}

}
 
源代码27 项目: james-project   文件: GetMessageListMethodTest.java
@Category(BasicFeature.class)
@Test
public void getMessageListShouldReturnAllMessagesOfCurrentUserOnlyWhenMultipleMailboxesAndNoParameters() throws Exception {
    String otherUser = "[email protected]" + DOMAIN;
    String password = "password";
    dataProbe.addUser(otherUser, password);

    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, ALICE.asString(), "mailbox");
    ComposedMessageId message1 = mailboxProbe.appendMessage(ALICE.asString(), ALICE_MAILBOX,
            new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()), new Date(), false, new Flags());

    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, ALICE.asString(), "mailbox2");
    ComposedMessageId message2 = mailboxProbe.appendMessage(ALICE.asString(), MailboxPath.forUser(ALICE, "mailbox2"),
            new ByteArrayInputStream("Subject: test2\r\n\r\ntestmail".getBytes()), new Date(), false, new Flags());
    await();

    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, otherUser, "mailbox");
    mailboxProbe.appendMessage(otherUser, MailboxPath.forUser(Username.of(otherUser), "mailbox"),
            new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()), new Date(), false, new Flags());
    await();

    given()
        .header("Authorization", aliceAccessToken.asString())
        .body("[[\"getMessageList\", {}, \"#0\"]]")
    .when()
        .post("/jmap")
    .then()
        .statusCode(200)
        .body(NAME, equalTo("messageList"))
        .body(ARGUMENTS + ".messageIds", containsInAnyOrder(message1.getMessageId().serialize(), message2.getMessageId().serialize()));
}
 
源代码28 项目: HttpSessionReplacer   文件: TestWebXmlParser.java
@Test
public void testDistributable() throws IOException {
  String webXml = Descriptors.create(WebAppDescriptor.class).version("3.0").distributable().exportAsString();
  try (ByteArrayInputStream bais = new ByteArrayInputStream(webXml.getBytes("UTF-8"))) {
    SessionConfiguration sessionConfiguration = new SessionConfiguration();
    sessionConfiguration.setDistributable(false);
    WebXmlParser.parseStream(sessionConfiguration, bais);
    assertEquals(1800, sessionConfiguration.getMaxInactiveInterval());
    assertTrue(sessionConfiguration.isDistributable());
  }
}
 
源代码29 项目: terracotta-platform   文件: ClusterTest.java
@SuppressWarnings("unchecked")
private static <T> T copy(T o) throws IOException, ClassNotFoundException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(baos);
  oos.writeObject(o);
  oos.close();
  ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
  return (T) in.readObject();
}
 
/**
 * Writes data to the stream and returns the size of the file.
 */
private void flowBytes(byte[] bytes, OutputStream output)
        throws IOException {
    // Could use output.write(), but IOTools writes in small portions, and
    // that is more natural
    ByteArrayInputStream byteInStream = new ByteArrayInputStream(bytes);
    try {
        IOTools.flow(byteInStream, output);
    } finally {
        byteInStream.close();
    }
}
 
 类所在包
 同包方法