ObjectOutputStream
import java.io.*;
import java.io.ObjectOutputStream;
public class SaverAddIntBean{
public static void main(String args[]){
new SaverAddIntBean().write();
}
public void write(){
FileOutputStream fos = null;
ObjectOutputStream oos = null;
AddInt ai = new AddInt();
ai.calc(1,2,3,4);
String path = "IntBean.ser";
try{
fos = new FileOutputStream(path);
oos = new ObjectOutputStream(fos);
oos.writeObject(ai);
System.out.println("Successfully");
}catch(NotSerializableException ie){
System.out.println("Error NotSerializableException.");
ie.printStackTrace();
}catch(IOException e){
System.out.println("Error IOException.");
e.printStackTrace();
}finally{
try{
oos.close();
fos.close();
}catch(IOException e){
}
}
}
public class AddInt implements Serializable{
private static final long serialVersionUID = 6128016096756071380L;
private int sum = 0;
public void calc(int... c){
for(int i = 0 ; i < c.length ; i++){
sum +=c[i];
}
}
public int getSum(){
return sum;
}
}
}
Error NotSerializableException.
java.io.NotSerializableException: SaverAddIntBean
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at SaverAddIntBean.write(SaverAddIntBean.java:16)
at SaverAddIntBean.main(SaverAddIntBean.java:5)
不知道為什麼一值出現這個例外訊息~.~
但是如果把public class AddInt implements Serializable加上static,
public static class AddInt implements Serializable就可以了,
雖這樣不太正確, 但是可以執行,
之後要好好看一下.
AddIntReadBean
import java.io.*;
public class AddIntReadBean{
public static void main(String args[]){
FileInputStream fis = null;
ObjectInputStream ois = null;
AddInt ai = null;
String path = "IntBean.ser";
try{
System.out.println("1-----------");
fis = new FileInputStream(path);
ois = new ObjectInputStream(fis);
System.out.println("2-----------");
ai = (AddInt)ois.readObject();
//String s2 = new String(ai);
System.out.println(ai);
System.out.println("3-----------");
if(ai != null){
System.out.println("Sum:"+ai.getSum());
}else{
System.out.println("null");
}
}catch(IOException e){
}catch(ClassNotFoundException e){
}finally{
try{
ois.close();
fis.close();
}catch(IOException e){
}
}
}
public static class AddInt implements Serializable{
private static final long serialVersionUID = 6128016096756071380L;
private int sum = 0;
public void calc(int... c){
for(int i = 0 ; i < c.length ; i++){
sum +=c[i];
}
}
//System.out.println("4-----------");
public int getSum(){
System.out.println("5-----------");
return sum;
}
}
}
................為啥拿不出來,
明明就是執行成功.
沒有留言:
張貼留言