下面列出了怎么用java.io.ObjectInputStream的API类实例代码及写法,或者点击链接到github查看源代码。
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
// Don't call defaultReadObject()
// Read in serialized fields
ObjectInputStream.GetField gfields = in.readFields();
// Get permissions
// writeObject writes a Hashtable<Class<?>, PermissionCollection> for
// the perms key, so this cast is safe, unless the data is corrupt.
@SuppressWarnings("unchecked")
Hashtable<Permission, Permission> perms =
(Hashtable<Permission, Permission>)gfields.get("perms", null);
permsMap = new HashMap<Permission, Permission>(perms.size()*2);
permsMap.putAll(perms);
}
/**
* Write and read int values to/from a stream. The benchmark is run in
* batches: each "batch" consists of a fixed number of read/write cycles,
* and the stream is flushed (and underlying stream buffer cleared) in
* between each batch.
* Arguments: <# batches> <# cycles per batch>
*/
public long run(String[] args) throws Exception {
int nbatches = Integer.parseInt(args[0]);
int ncycles = Integer.parseInt(args[1]);
StreamBuffer sbuf = new StreamBuffer();
ObjectOutputStream oout =
new ObjectOutputStream(sbuf.getOutputStream());
ObjectInputStream oin =
new ObjectInputStream(sbuf.getInputStream());
doReps(oout, oin, sbuf, 1, ncycles); // warmup
long start = System.currentTimeMillis();
doReps(oout, oin, sbuf, nbatches, ncycles);
return System.currentTimeMillis() - start;
}
/**
* In general, this method will only be used by generated code. However, it may be suitable
* to use this method in some cases (such as in a WearableListenerService).
*
* Unpacks the given byte array into an object.
*
* This method will use the {@link java.io.Serializable} system to deserialize the data.
*
* @param data The byte array to deserialize into an object.
* @return An object deserialized from the byte array.
*/
@SuppressWarnings("unchecked")
public static <T> T unpackSerializable(byte[] data) {
if(data==null || data.length==0) {
return null;
}
try {
final ByteArrayInputStream bytes = new ByteArrayInputStream(data);
final ObjectInputStream in = new ObjectInputStream(bytes);
return (T)in.readObject();
}catch (Exception e){
throw new IllegalArgumentException("Unable to deserialize object", e);
}
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
// Don't call defaultReadObject()
// Read in serialized fields
ObjectInputStream.GetField gfields = in.readFields();
// Get allPermission
allPermission = (PermissionCollection) gfields.get("allPermission", null);
// Get permissions
// writeObject writes a Hashtable<Class<?>, PermissionCollection> for
// the perms key, so this cast is safe, unless the data is corrupt.
@SuppressWarnings("unchecked")
Hashtable<Class<?>, PermissionCollection> perms =
(Hashtable<Class<?>, PermissionCollection>)gfields.get("perms", null);
permsMap = new HashMap<Class<?>, PermissionCollection>(perms.size()*2);
permsMap.putAll(perms);
// Set hasUnresolved
UnresolvedPermissionCollection uc =
(UnresolvedPermissionCollection) permsMap.get(UnresolvedPermission.class);
hasUnresolved = (uc != null && uc.elements().hasMoreElements());
}
/**
* Write and read object arrays to/from a stream. The benchmark is run in
* batches, with each batch consisting of a fixed number of read/write
* cycles. The ObjectOutputStream is reset after each batch of cycles has
* completed.
* Arguments: <array size> <# batches> <# cycles per batch>
*/
public long run(String[] args) throws Exception {
int size = Integer.parseInt(args[0]);
int nbatches = Integer.parseInt(args[1]);
int ncycles = Integer.parseInt(args[2]);
Node[][] arrays = genArrays(size, ncycles);
StreamBuffer sbuf = new StreamBuffer();
ObjectOutputStream oout =
new ObjectOutputStream(sbuf.getOutputStream());
ObjectInputStream oin =
new ObjectInputStream(sbuf.getInputStream());
doReps(oout, oin, sbuf, arrays, 1); // warmup
long start = System.currentTimeMillis();
doReps(oout, oin, sbuf, arrays, nbatches);
return System.currentTimeMillis() - start;
}
@Test
public void testSerialization()
throws Throwable {
Configuration c = new Configuration();
c.set("foo", "bar");
c.registerSerializer(new PointSerializer());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(c);
out.close();
bos.close();
byte[] bytes = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(bis);
Configuration sc = (Configuration) in.readObject();
in.close();
bis.close();
Assert.assertEquals(sc, c);
}
public static Blacklist getInstance(Context context) {
if(theInstance == null)
try {
FileInputStream fileInputStream = context.openFileInput("Blacklist");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
theInstance = (Blacklist) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
theInstance = new Blacklist();
}
return theInstance;
}
/**
* De-Serialize a BatchUpdateException from JDBC 4.0 and make sure you can
* read it back properly
*/
@Test
public void test13() throws Exception {
String reason1 = "This was the error msg";
String state1 = "user defined sqlState";
String cause1 = "java.lang.Throwable: throw 1";
int errorCode1 = 99999;
Throwable t = new Throwable("throw 1");
int[] uc1 = {1, 2, 21};
long[] luc1 = {1, 2, 21};
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(SerializedBatchUpdateException.DATA));
BatchUpdateException bue = (BatchUpdateException) ois.readObject();
assertTrue(reason1.equals(bue.getMessage())
&& bue.getSQLState().equals(state1)
&& bue.getErrorCode() == errorCode1
&& cause1.equals(bue.getCause().toString())
&& Arrays.equals(bue.getLargeUpdateCounts(), luc1)
&& Arrays.equals(bue.getUpdateCounts(), uc1));
}
static void testSerialization() throws Exception {
Currency currency1 = Currency.getInstance("DEM");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oStream = new ObjectOutputStream(baos);
oStream.writeObject(currency1);
oStream.flush();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream iStream = new ObjectInputStream(bais);
Currency currency2 = (Currency) iStream.readObject();
if (currency1 != currency2) {
throw new RuntimeException("serialization breaks class invariant");
}
}
RepositoryImpl(ORB orb, File dbDir, boolean debug)
{
this.debug = debug ;
this.orb = orb;
wrapper = ActivationSystemException.get( orb, CORBALogDomains.ORBD_REPOSITORY ) ;
// if databse does not exist, create it otherwise read it in
File dbFile = new File(dbDir, "servers.db");
if (!dbFile.exists()) {
db = new RepositoryDB(dbFile);
db.flush();
} else {
try {
FileInputStream fis = new FileInputStream(dbFile);
ObjectInputStream ois = new ObjectInputStream(fis);
db = (RepositoryDB) ois.readObject();
ois.close();
} catch (Exception e) {
throw wrapper.cannotReadRepositoryDb( e ) ;
}
}
// export the repository
orb.connect(this);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
EmptyBlock b1 = new EmptyBlock(1.0, 2.0);
EmptyBlock b2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(b1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
b2 = (EmptyBlock) in.readObject();
in.close();
}
catch (Exception e) {
fail(e.toString());
}
assertEquals(b1, b2);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
ShortTextTitle t1 = new ShortTextTitle("ABC");
ShortTextTitle t2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(t1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
t2 = (ShortTextTitle) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(t1, t2);
}
/**
* Accesses parameter tool parameters and then serializes the given parameter tool and deserializes again.
* @param parameterTool to serialize/deserialize
*/
private void serializeDeserialize(ParameterTool parameterTool) throws IOException, ClassNotFoundException {
// weirdly enough, this call has side effects making the ParameterTool serialization fail if not
// using a concurrent data structure.
parameterTool.get(UUID.randomUUID().toString());
try (
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(parameterTool);
oos.close();
baos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
// this should work :-)
ParameterTool deserializedParameterTool = ((ParameterTool) ois.readObject());
}
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.angleGridlineStroke = SerialUtilities.readStroke(stream);
this.angleGridlinePaint = SerialUtilities.readPaint(stream);
this.radiusGridlineStroke = SerialUtilities.readStroke(stream);
this.radiusGridlinePaint = SerialUtilities.readPaint(stream);
this.angleLabelPaint = SerialUtilities.readPaint(stream);
if (this.axis != null) {
this.axis.setPlot(this);
this.axis.addChangeListener(this);
}
if (this.dataset != null) {
this.dataset.addChangeListener(this);
}
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
listeningStyles = new Vector<Style>();
s.defaultReadObject();
// Reinstall style listeners.
if (styleContextChangeListener == null &&
listenerList.getListenerCount(DocumentListener.class) > 0) {
styleContextChangeListener = createStyleContextChangeListener();
if (styleContextChangeListener != null) {
StyleContext styles = (StyleContext)getAttributeContext();
styles.addChangeListener(styleContextChangeListener);
}
updateStylesListeningTo();
}
}
public static void main(final String[] args) throws Exception {
Hashtable<String, String> h1 = new Hashtable<>();
System.err.println("*** BEGIN TEST ***");
h1.put("key", "value");
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(h1);
}
final byte[] data = baos.toByteArray();
final ByteArrayInputStream bais = new ByteArrayInputStream(data);
final Object deserializedObject;
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
deserializedObject = ois.readObject();
}
if(!h1.getClass().isInstance(deserializedObject)) {
throw new RuntimeException("Result not assignable to type of h1");
}
if (false == h1.equals(deserializedObject)) {
Hashtable<String, String> d1 = (Hashtable<String, String>) h1;
for(Map.Entry entry: h1.entrySet()) {
System.err.println("h1.key::" + entry.getKey() + " d1.containsKey()::" + d1.containsKey((String) entry.getKey()));
System.err.println("h1.value::" + entry.getValue() + " d1.contains()::" + d1.contains(entry.getValue()));
System.err.println("h1.value == d1.value " + entry.getValue().equals(d1.get((String) entry.getKey())));
}
throw new RuntimeException(getFailureText(h1, deserializedObject));
}
}
private void readObject(ObjectInputStream stream)
throws ClassNotFoundException, IOException {
stream.defaultReadObject();
if (reason == null) {
reason = BasicReason.UNSPECIFIED;
}
if (certPath == null && index != -1) {
throw new InvalidObjectException("certpath is null and index != -1");
}
if (index < -1 ||
(certPath != null && index >= certPath.getCertificates().size())) {
throw new InvalidObjectException("index out of range");
}
}
/**
* readObject is called to restore the state of the
* DelegationPermission from a stream.
*/
private synchronized void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the action, then initialize the rest
s.defaultReadObject();
init(getName());
}
/** */
@SuppressWarnings("unchecked")
public default void externalizeTest(T initObj) {
T objRestored = null;
try {
ByteArrayOutputStream byteArrOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objOutputStream = new ObjectOutputStream(byteArrOutputStream);
objOutputStream.writeObject(initObj);
ByteArrayInputStream byteArrInputStream = new ByteArrayInputStream(byteArrOutputStream.toByteArray());
ObjectInputStream objInputStream = new ObjectInputStream(byteArrInputStream);
objRestored = (T)objInputStream.readObject();
assertTrue(MathTestConstants.VAL_NOT_EQUALS, initObj.equals(objRestored));
assertTrue(MathTestConstants.VAL_NOT_EQUALS, Integer.compare(initObj.hashCode(), objRestored.hashCode()) == 0);
}
catch (ClassNotFoundException | IOException e) {
fail(e + " [" + e.getMessage() + "]");
}
finally {
if (objRestored != null && objRestored instanceof Destroyable)
((Destroyable)objRestored).destroy();
}
}
/**
* Reads this object out of a serialization stream, handling
* objects written by older versions of the class that didn't contain all
* of the fields we use now..
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
if (serialVersionOnStream < 1) {
// "newAlign" field wasn't present, so use the old "align" field.
setAlignment(this.align);
}
serialVersionOnStream = currentSerialVersion;
}
/**
* Initializes the {@code when} field if it is not present in the
* object input stream. In that case, the field will be initialized by
* invoking {@link java.awt.EventQueue#getMostRecentEventTime()}.
*/
private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
s.defaultReadObject();
if (when == 0) {
// Can't use getMostRecentEventTimeForSource because source is always null during deserialization
when = EventQueue.getMostRecentEventTime();
}
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.paint = SerialUtilities.readPaint(stream);
this.backgroundPaint = SerialUtilities.readPaint(stream);
this.outlinePaint = SerialUtilities.readPaint(stream);
this.outlineStroke = SerialUtilities.readStroke(stream);
}
private void readObject(
ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
byte[] enc = (byte[])in.readObject();
populateFromPubKeyInfo(SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(enc)));
}
private static <T> T serialize(T x) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(x);
oout.close();
byte[] bytes = bout.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
ObjectInputStream oin = new ObjectInputStream(bin);
return (T) oin.readObject();
}
/** Read the object from Base64 string. */
public static Object fromString( String s ) throws IOException,
ClassNotFoundException {
byte [] data = Base64.decode(s, Base64.DEFAULT);
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( data ) );
Object o = ois.readObject();
ois.close();
return o;
}
@Test
public void testDestroyEnumSingleton() throws Exception {
EnumSingleton instance = EnumSingleton.INSTANCE;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(instance);
try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis)) {
EnumSingleton copy = (EnumSingleton) ois.readObject();
assertEquals(instance, copy);
}
}
}
/**
* Deserializes this <code>DragSource</code>. This method first performs
* default deserialization. Next, this object's <code>FlavorMap</code> is
* deserialized by using the next object in the stream.
* If the resulting <code>FlavorMap</code> is <code>null</code>, this
* object's <code>FlavorMap</code> is set to the default FlavorMap for
* this thread's <code>ClassLoader</code>.
* Next, this object's listeners are deserialized by reading a
* <code>null</code>-terminated sequence of 0 or more key/value pairs
* from the stream:
* <ul>
* <li>If a key object is a <code>String</code> equal to
* <code>dragSourceListenerK</code>, a <code>DragSourceListener</code> is
* deserialized using the corresponding value object and added to this
* <code>DragSource</code>.
* <li>If a key object is a <code>String</code> equal to
* <code>dragSourceMotionListenerK</code>, a
* <code>DragSourceMotionListener</code> is deserialized using the
* corresponding value object and added to this <code>DragSource</code>.
* <li>Otherwise, the key/value pair is skipped.
* </ul>
*
* @see java.awt.datatransfer.SystemFlavorMap#getDefaultFlavorMap
* @since 1.4
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
// 'flavorMap' was written explicitly
flavorMap = (FlavorMap)s.readObject();
// Implementation assumes 'flavorMap' is never null.
if (flavorMap == null) {
flavorMap = SystemFlavorMap.getDefaultFlavorMap();
}
Object keyOrNull;
while (null != (keyOrNull = s.readObject())) {
String key = ((String)keyOrNull).intern();
if (dragSourceListenerK == key) {
addDragSourceListener((DragSourceListener)(s.readObject()));
} else if (dragSourceMotionListenerK == key) {
addDragSourceMotionListener(
(DragSourceMotionListener)(s.readObject()));
} else {
// skip value for unrecognized key
s.readObject();
}
}
}
/**
* Reads the {@code ObjectInputStream} and an optional
* list of listeners to receive various events fired by
* the component; also reads a list of
* (possibly {@code null}) child windows.
* Unrecognized keys or values will be ignored.
*
* @param s the {@code ObjectInputStream} to read
* @exception HeadlessException if
* {@code GraphicsEnvironment.isHeadless} returns
* {@code true}
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #writeObject
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException, HeadlessException
{
GraphicsEnvironment.checkHeadless();
initDeserializedWindow();
ObjectInputStream.GetField f = s.readFields();
syncLWRequests = f.get("syncLWRequests", systemSyncLWRequests);
state = f.get("state", 0);
focusableWindowState = f.get("focusableWindowState", true);
windowSerializedDataVersion = f.get("windowSerializedDataVersion", 1);
locationByPlatform = f.get("locationByPlatform", locationByPlatformProp);
// Note: 1.4 (or later) doesn't use focusMgr
focusMgr = (FocusManager)f.get("focusMgr", null);
Dialog.ModalExclusionType et = (Dialog.ModalExclusionType)
f.get("modalExclusionType", Dialog.ModalExclusionType.NO_EXCLUDE);
setModalExclusionType(et); // since 6.0
boolean aot = f.get("alwaysOnTop", false);
if(aot) {
setAlwaysOnTop(aot); // since 1.5; subject to permission check
}
shape = (Shape)f.get("shape", null);
opacity = (Float)f.get("opacity", 1.0f);
this.securityWarningWidth = 0;
this.securityWarningHeight = 0;
this.securityWarningPointX = 2.0;
this.securityWarningPointY = 0.0;
this.securityWarningAlignmentX = RIGHT_ALIGNMENT;
this.securityWarningAlignmentY = TOP_ALIGNMENT;
deserializeResources(s);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.shape = SerialUtilities.readShape(stream);
this.fillPaint = SerialUtilities.readPaint(stream);
this.outlinePaint = SerialUtilities.readPaint(stream);
this.outlineStroke = SerialUtilities.readStroke(stream);
this.line = SerialUtilities.readShape(stream);
this.linePaint = SerialUtilities.readPaint(stream);
this.lineStroke = SerialUtilities.readStroke(stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.store = new TreeMap();
int keyCount = stream.readInt();
for (int i = 0; i < keyCount; i++) {
Comparable key = (Comparable) stream.readObject();
Stroke stroke = SerialUtilities.readStroke(stream);
this.store.put(key, stroke);
}
}