java.io.ObjectOutputStream#writeObject ( )源码实例Demo

下面列出了java.io.ObjectOutputStream#writeObject ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: j2objc   文件: SerializationTest.java
public void testSerializationPkgPrefixes() throws IOException, ClassNotFoundException {
  Hello greeting = new Hello("hello", "world", 42);
  assertEquals("hello, world!", greeting.toString());
  assertEquals(42, greeting.getN());

  // Save the greeting to a file.
  ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(TEST_FILE_NAME));
  out.writeObject(greeting);
  out.close();
  File binFile = new File(TEST_FILE_NAME);
  assertTrue(binFile.exists());

  // Read back the greeting.
  ObjectInputStream in = new ObjectInputStream(new FileInputStream(TEST_FILE_NAME));
  Hello greeting2 = (Hello) in.readObject();
  in.close();
  assertEquals("hello, world!", greeting.toString());
  assertEquals(0, greeting2.getN());  // 0 because n is transient.
  
  // Verify package prefix was used.
  assertEquals("CTHello", objectiveCClassName(greeting2));
}
 
源代码2 项目: rdf4j   文件: RDFStoreTest.java
@Test
public void testStatementSerialization() throws Exception {
	Statement st = vf.createStatement(picasso, RDF.TYPE, painter);

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ObjectOutputStream out = new ObjectOutputStream(baos);
	out.writeObject(st);
	out.close();

	ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
	ObjectInputStream in = new ObjectInputStream(bais);
	Statement deserializedStatement = (Statement) in.readObject();
	in.close();

	Assert.assertTrue(st.equals(deserializedStatement));
}
 
源代码3 项目: hottub   文件: CharArrays.java
/**
 * Run benchmark for given number of batches, with given number of cycles
 * for each batch.
 */
void doReps(ObjectOutputStream oout, ObjectInputStream oin,
            StreamBuffer sbuf, char[][] arrays, int nbatches)
    throws Exception
{
    int ncycles = arrays.length;
    for (int i = 0; i < nbatches; i++) {
        sbuf.reset();
        oout.reset();
        for (int j = 0; j < ncycles; j++) {
            oout.writeObject(arrays[j]);
        }
        oout.flush();
        for (int j = 0; j < ncycles; j++) {
            oin.readObject();
        }
    }
}
 
源代码4 项目: jdk8u-jdk   文件: ImageIcon.java
private void writeObject(ObjectOutputStream s)
    throws IOException
{
    s.defaultWriteObject();

    int w = getIconWidth();
    int h = getIconHeight();
    int[] pixels = image != null? new int[w * h] : null;

    if (image != null) {
        try {
            PixelGrabber pg = new PixelGrabber(image, 0, 0, w, h, pixels, 0, w);
            pg.grabPixels();
            if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
                throw new IOException("failed to load image contents");
            }
        }
        catch (InterruptedException e) {
            throw new IOException("image load interrupted");
        }
    }

    s.writeInt(w);
    s.writeInt(h);
    s.writeObject(pixels);
}
 
源代码5 项目: TencentKona-8   文件: Strings.java
/**
 * Run benchmark for given number of batches, with given number of cycles
 * for each batch.
 */
void doReps(ObjectOutputStream oout, ObjectInputStream oin,
            StreamBuffer sbuf, String[] strs, int nbatches, int ncycles)
    throws Exception
{
    for (int i = 0; i < nbatches; i++) {
        sbuf.reset();
        oout.reset();
        for (int j = 0; j < ncycles; j++) {
            oout.writeObject(strs[j]);
        }
        oout.flush();
        for (int j = 0; j < ncycles; j++) {
            oin.readObject();
        }
    }
}
 
源代码6 项目: jdk8u-dev-jdk   文件: NulFile.java
private static void testSerialization(File testFile) {
    String path = testFile.getPath();
    try {
        // serialize test file
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(testFile);
        oos.close();
        // deserialize test file
        byte[] bytes = baos.toByteArray();
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(is);
        File newFile = (File) ois.readObject();
        // test
        String newPath = newFile.getPath();
        if (!path.equals(newPath)) {
            throw new RuntimeException(
                    "Serialization should not change file path");
        }
        test(newFile, false);
    } catch (IOException | ClassNotFoundException ex) {
        System.err.println("Exception happens in testSerialization");
        System.err.println(ex.getMessage());
    }
}
 
源代码7 项目: astor   文件: TestDateTime_Basics.java
public void testSerialization() throws Exception {
    DateTime test = new DateTime(TEST_TIME_NOW);
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(test);
    byte[] bytes = baos.toByteArray();
    oos.close();
    
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bais);
    DateTime result = (DateTime) ois.readObject();
    ois.close();
    
    assertEquals(test, result);
}
 
public static void main(String[] args) throws Exception
{
    RemotableInputStream remotableInputStream = new RemotableInputStream(InetAddress.getLocalHost().getHostName(), 7777, new ByteArrayInputStream("test".getBytes()));

    for (int b = -1; (b = remotableInputStream.read()) != -1;)
    {
        System.out.println((char) b);
    }

    remotableInputStream = new RemotableInputStream(InetAddress.getLocalHost().getHostName(), 7777, new ByteArrayInputStream("test".getBytes()));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(remotableInputStream);

    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    remotableInputStream = (RemotableInputStream) ois.readObject();

    for (int b = -1; (b = remotableInputStream.read()) != -1;)
    {
        System.out.println((char) b);
    }
    remotableInputStream.close();
}
 
源代码9 项目: openjdk-8   文件: IntArrays.java
/**
 * Run benchmark for given number of batches, with given number of cycles
 * for each batch.
 */
void doReps(ObjectOutputStream oout, ObjectInputStream oin,
            StreamBuffer sbuf, int[][] arrays, int nbatches)
    throws Exception
{
    int ncycles = arrays.length;
    for (int i = 0; i < nbatches; i++) {
        sbuf.reset();
        oout.reset();
        for (int j = 0; j < ncycles; j++) {
            oout.writeObject(arrays[j]);
        }
        oout.flush();
        for (int j = 0; j < ncycles; j++) {
            oin.readObject();
        }
    }
}
 
源代码10 项目: dubbox   文件: TelnetCodecTest.java
protected byte[] objectToByte(Object obj){
    byte[] bytes; 
    if (obj instanceof String){
        bytes = ((String)obj).getBytes();
    } else if (obj instanceof byte[]){
        bytes = (byte[]) obj;
    } else {
        try { 
            //object to bytearray 
            ByteArrayOutputStream bo = new ByteArrayOutputStream(); 
            ObjectOutputStream oo = new ObjectOutputStream(bo); 
            oo.writeObject(obj); 
            bytes = bo.toByteArray(); 
            bo.close(); 
            oo.close();     
        } 
        catch(Exception e){ 
            throw new RuntimeException(e);
        } 
    }
    return(bytes); 
}
 
@Test
public void testCreateSingleSerializableTaskVariable() throws Exception {
    repositoryService.createDeployment()
            .addClasspathResource("org/flowable/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml")
            .deploy();

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();

    TestSerializableVariable serializable = new TestSerializableVariable();
    serializable.setSomeField("some value");

    // Serialize object to readable stream for representation
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ObjectOutputStream output = new ObjectOutputStream(buffer);
    output.writeObject(serializable);
    output.close();

    InputStream binaryContent = new ByteArrayInputStream(buffer.toByteArray());

    // Add name, type and scope
    Map<String, String> additionalFields = new HashMap<>();
    additionalFields.put("name", "serializableVariable");
    additionalFields.put("type", "serializable");

    HttpPost httpPost = new HttpPost(serverUrlPrefix +
            RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
    httpPost.setEntity(HttpMultipartHelper.getMultiPartEntity("value", "application/x-java-serialized-object", binaryContent, additionalFields));

    // We have serializeable object disabled, we should get a 415.
    assertResponseStatus(httpPost, HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE);
}
 
源代码12 项目: jdk8u-jdk   文件: Test4165217.java
private static byte[] serialize(Object object) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(object);
    oos.flush();
    return baos.toByteArray();
}
 
源代码13 项目: incubator-samoa   文件: SerializableSerializer.java
@Override
public void write(Kryo kryo, Output output, Object object) {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try {
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(object);
    oos.flush();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  byte[] ser = bos.toByteArray();
  output.writeInt(ser.length);
  output.writeBytes(ser);
}
 
源代码14 项目: TencentKona-8   文件: RMIConnectorServer.java
static String encodeJRMPStub(
        RMIServer rmiServer, Map<String, ?> env)
        throws IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream oout = new ObjectOutputStream(bout);
    oout.writeObject(rmiServer);
    oout.close();
    byte[] bytes = bout.toByteArray();
    return byteArrayToBase64(bytes);
}
 
源代码15 项目: tsml   文件: BOSSC45.java
public boolean storeAndClearClassifier() {
    try {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
        out.writeObject(this);
        out.close();   
        clearClassifier();
        return true;
    }catch(IOException e) {
        System.out.print("Error serialiszing to " + filename);
        e.printStackTrace();
        return false;
    }
}
 
源代码16 项目: RetrofitClient   文件: PersistentCookieStore.java
/**
 * cookies 序列化成 string
 *
 * @param cookie 要序列化的cookie
 * @return 序列化之后的string
 */
protected String encodeCookie(SerializableOkHttpCookies cookie) {
    if (cookie == null)
        return null;
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        ObjectOutputStream outputStream = new ObjectOutputStream(os);
        outputStream.writeObject(cookie);
    } catch (IOException e) {
        Log.d(LOG_TAG, "IOException in encodeCookie", e);
        return null;
    }

    return byteArrayToHexString(os.toByteArray());
}
 
源代码17 项目: HubPlayer   文件: HubFrame.java
private void saveSongLibrary() {

		if (songLibrary != null) {
			songLibrary.setBufferedDateTime(new Date().getTime());
			try {
				ObjectOutputStream outputStream = new ObjectOutputStream(
						new FileOutputStream(new File("E:/Hub/SongLibrary.dat")));
				outputStream.writeObject(songLibrary);
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
 
源代码18 项目: openjdk-8-source   文件: Calendar.java
/**
 * Save the state of this object to a stream (i.e., serialize it).
 *
 * Ideally, <code>Calendar</code> would only write out its state data and
 * the current time, and not write any field data out, such as
 * <code>fields[]</code>, <code>isTimeSet</code>, <code>areFieldsSet</code>,
 * and <code>isSet[]</code>.  <code>nextStamp</code> also should not be part
 * of the persistent state. Unfortunately, this didn't happen before JDK 1.1
 * shipped. To be compatible with JDK 1.1, we will always have to write out
 * the field values and state flags.  However, <code>nextStamp</code> can be
 * removed from the serialization stream; this will probably happen in the
 * near future.
 */
private synchronized void writeObject(ObjectOutputStream stream)
     throws IOException
{
    // Try to compute the time correctly, for the future (stream
    // version 2) in which we don't write out fields[] or isSet[].
    if (!isTimeSet) {
        try {
            updateTime();
        }
        catch (IllegalArgumentException e) {}
    }

    // If this Calendar has a ZoneInfo, save it and set a
    // SimpleTimeZone equivalent (as a single DST schedule) for
    // backward compatibility.
    TimeZone savedZone = null;
    if (zone instanceof ZoneInfo) {
        SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance();
        if (stz == null) {
            stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID());
        }
        savedZone = zone;
        zone = stz;
    }

    // Write out the 1.1 FCS object.
    stream.defaultWriteObject();

    // Write out the ZoneInfo object
    // 4802409: we write out even if it is null, a temporary workaround
    // the real fix for bug 4844924 in corba-iiop
    stream.writeObject(savedZone);
    if (savedZone != null) {
        zone = savedZone;
    }
}
 
源代码19 项目: jelectrum   文件: ObjectConversionMap.java
private ByteString convertV(V value)
  throws java.io.IOException
{
  ByteString b = null;
  if (value != null)
  {
    if (mode==ConversionMode.STRING)
    {
      b = ByteString.copyFromUtf8(value.toString());
    }
    if (mode==ConversionMode.SHA256HASH)
    {
      Sha256Hash h = (Sha256Hash) value;
      b = ByteString.copyFrom(h.getBytes());
    }
    if (mode==ConversionMode.OBJECT)
    {
      try
      {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oout = new ObjectOutputStream(bout);
        oout.writeObject(value);
        oout.flush();
        b = ByteString.copyFrom(bout.toByteArray());

        //System.out.println("" + value.getClass().getName() + " - " + b.size());

      }
      catch(java.io.IOException e)
      {
        throw new RuntimeException(e);
      }

    }
    if (mode==ConversionMode.SERIALIZEDTRANSACTION)
    {
      SerializedTransaction stx = (SerializedTransaction)value;
      b = ByteString.copyFrom(stx.getBytes());
    }
    if (mode==ConversionMode.STOREDBLOCK)
    {
      StoredBlock sb = (StoredBlock) value;
      byte[] buff = new byte[StoredBlock.COMPACT_SERIALIZED_SIZE];
      sb.serializeCompact(ByteBuffer.wrap(buff));
      b = ByteString.copyFrom(buff);
    }
    if (mode==ConversionMode.EXISTENCE)
    {
      byte[] b1= new byte[1];
      b = ByteString.copyFrom(b1);
    }


  }
  return b;

}
 
源代码20 项目: astor   文件: ThreeEighthesStepInterpolatorTest.java
@Test
public void serialization()
  throws IOException, ClassNotFoundException,
         DimensionMismatchException, NumberIsTooSmallException,
         MaxCountExceededException, NoBracketingException {

  TestProblem3 pb = new TestProblem3(0.9);
  double step = (pb.getFinalTime() - pb.getInitialTime()) * 0.0003;
  ThreeEighthesIntegrator integ = new ThreeEighthesIntegrator(step);
  integ.addStepHandler(new ContinuousOutputModel());
  integ.integrate(pb,
                  pb.getInitialTime(), pb.getInitialState(),
                  pb.getFinalTime(), new double[pb.getDimension()]);

  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ObjectOutputStream    oos = new ObjectOutputStream(bos);
  for (StepHandler handler : integ.getStepHandlers()) {
      oos.writeObject(handler);
  }

  Assert.assertTrue(bos.size () > 880000);
  Assert.assertTrue(bos.size () < 900000);

  ByteArrayInputStream  bis = new ByteArrayInputStream(bos.toByteArray());
  ObjectInputStream     ois = new ObjectInputStream(bis);
  ContinuousOutputModel cm  = (ContinuousOutputModel) ois.readObject();

  Random random = new Random(347588535632l);
  double maxError = 0.0;
  for (int i = 0; i < 1000; ++i) {
    double r = random.nextDouble();
    double time = r * pb.getInitialTime() + (1.0 - r) * pb.getFinalTime();
    cm.setInterpolatedTime(time);
    double[] interpolatedY = cm.getInterpolatedState ();
    double[] theoreticalY  = pb.computeTheoreticalState(time);
    double dx = interpolatedY[0] - theoreticalY[0];
    double dy = interpolatedY[1] - theoreticalY[1];
    double error = dx * dx + dy * dy;
    if (error > maxError) {
      maxError = error;
    }
  }

  Assert.assertTrue(maxError > 0.005);

}