Java Code Examples for java.io.ObjectOutputStream#writeObject()
The following examples show how to use
java.io.ObjectOutputStream#writeObject() .
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: SerializationTest.java From j2objc with Apache License 2.0 | 6 votes |
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)); }
Example 2
Source File: TelnetCodecTest.java From dubbox with Apache License 2.0 | 6 votes |
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); }
Example 3
Source File: IntArrays.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * 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(); } } }
Example 4
Source File: RemotableInputStream.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
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(); }
Example 5
Source File: TestDateTime_Basics.java From astor with GNU General Public License v2.0 | 6 votes |
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); }
Example 6
Source File: RDFStoreTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@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)); }
Example 7
Source File: NulFile.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
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()); } }
Example 8
Source File: CharArrays.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * 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(); } } }
Example 9
Source File: ImageIcon.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
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); }
Example 10
Source File: Strings.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * 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(); } } }
Example 11
Source File: Calendar.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
/** * 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; } }
Example 12
Source File: HubFrame.java From HubPlayer with GNU General Public License v3.0 | 5 votes |
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(); } } }
Example 13
Source File: PersistentCookieStore.java From RetrofitClient with Apache License 2.0 | 5 votes |
/** * 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()); }
Example 14
Source File: BOSSC45.java From tsml with GNU General Public License v3.0 | 5 votes |
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; } }
Example 15
Source File: RMIConnectorServer.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
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); }
Example 16
Source File: SerializableSerializer.java From incubator-samoa with Apache License 2.0 | 5 votes |
@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); }
Example 17
Source File: Test4165217.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
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(); }
Example 18
Source File: SerializableVariablesDiabledTest.java From flowable-engine with Apache License 2.0 | 5 votes |
@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); }
Example 19
Source File: ObjectConversionMap.java From jelectrum with MIT License | 4 votes |
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; }
Example 20
Source File: ThreeEighthesStepInterpolatorTest.java From astor with GNU General Public License v2.0 | 4 votes |
@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); }