📄 objectsaver.java
字号:
package examples.io;
import java.io.*;
/** A class defined to be used in
* serialization operations.
*/
class ObjectToSave implements Serializable {
static final long serialVersionUID
= 7482918152381158178L;
private int i;
private String s;
private transient double d;
public ObjectToSave( int i, String s, double d ) {
this.i = i;
this.s = s;
this.d = d;
}
public String toString() {
return "i = " + i + ", s = " + s + ", d = " + d;
}
private void readObject( ObjectInputStream ois )
throws ClassNotFoundException, IOException {
System.out.println( "deserializing..." );
ois.defaultReadObject();
System.out.println( "deserialized" );
}
private void writeObject( ObjectOutputStream oos )
throws IOException {
System.out.println( "serializing..." );
oos.defaultWriteObject();
System.out.println( "serialized" );
}
}
/** A class used to demonstrate serializing objects
* to and from a file.
*/
public class ObjectSaver {
private static final String FILE_NAME
= "objects.ser";
/** Test method for the class
* @param args not used
*/
public static void main( String[] args ) {
try {
// create the object to be serialized
ObjectToSave ots
= new ObjectToSave( 57, "pizza", 3.14 );
// create the target File object and erase
// any already existing file
File objectFile = new File( FILE_NAME );
if ( objectFile.exists() ) {
objectFile.delete();
}
// open the file, create the output stream
// and write the object
FileOutputStream fos
= new FileOutputStream( objectFile );
ObjectOutputStream oos
= new ObjectOutputStream( fos );
oos.writeObject( ots );
oos.close();
// reopen the file and retrieve the object
FileInputStream fis
= new FileInputStream( objectFile );
ObjectInputStream ois
= new ObjectInputStream( fis );
ObjectToSave retrieved
= (ObjectToSave) ois.readObject();
ois.close();
System.out.println( retrieved );
}
catch ( OptionalDataException x ) {
System.out.println( x );
x.printStackTrace();
}
catch ( ClassNotFoundException x ) {
System.out.println( x );
x.printStackTrace();
}
catch ( IOException x ) {
System.out.println( x );
x.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -