import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
public class ObjectReadAndWrite {
public void xuLieHua(File Filename, Object obj1) throws IOException {
FileOutputStream fos1 = new FileOutputStream(Filename);
ObjectOutputStream oos1 = new ObjectOutputStream(fos1);
oos1.writeObject(obj1);
System.out.println("序列化文件长度: " + Filename.length());
oos1.flush();
oos1.close();
}
public Object fanXuLieHua(File Filename) throws IOException,
ClassNotFoundException {
byte[] b = new byte[(int) Filename.length()];
FileInputStream fis1 = new FileInputStream(Filename);
ObjectInputStream ois1 = new ObjectInputStream(fis1);
BufferedInputStream bis1 = new BufferedInputStream(fis1);
Object obj1 = ois1.readObject();
// ois1.read(b);
bis1.read(b);
System.out.println("读出序列化文件长度: " + b.length);
System.out.println(b.toString());
System.out.println("" + Arrays.toString(b));
ois1.close();
return obj1;
}
}
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class TestObject {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
Object rh1 = null;
String[] file = { ".//file1.txt", ".//file2.txt", ".//file3.txt",
".//file4.txt", ".//file5.txt" };
for (int i = 0; i < 5; i++) {
switch (i) {
case 0:
rh1 = new RedHead();
break;
case 1:
rh1 = new Toy();
break;
case 2:
rh1 = new Test();
break;
case 3:
rh1 = new Input();
break;
}
File f1 = new File(file[i]);
if (!f1.exists()) {
f1.createNewFile();
}
System.out.println("所要序列化的文件存储目录: " + f1.getAbsolutePath());
// RedHead rh1 = new RedHead();
ObjectReadAndWrite orw = new ObjectReadAndWrite();
orw.xuLieHua(f1, rh1);
System.out.println("序列化完成!");
System.out.println("文件反序列化:");
RedHead rh2 = (RedHead) orw.fanXuLieHua(f1);
System.out.println("文件反序列化完成!");
}
}
}
import java.io.Serializable;
public class RedHead extends SingSong implements IyayaInterface,Serializable{
String[] name=null;
int age=0;
int high=0;
int weight=0;
@Override
public void run() {
System.out.println("\"running!Great RedHead \"");
}
@Override
public void fly() {
System.out.println("\"flying!Great RedHead \"");
}
@Override
public void swim() {
System.out.println("\"swiming!Great RedHead \"");
}
@Override
public void singOtherSong(int num) {
switch(num){
case 1:System.out.println("i am sing “江南style”");break;
case 2:System.out.println("i am sing “夏天的风”");break;
case 3:System.out.println("i am sing “唯一”");break;
case 4:System.out.println("i am sing “天空之城”");break;
default :System.out.println("i am sing “抗拒命运”");break;
}
}
}