import java.io.*;public class Test { public static void main(String[] args) {
File f1=new File("f:\\touch.txt");
Cat ca=new Test().new Cat(20,"Lucy");
try{
FileOutputStream fos=new FileOutputStream(f1);
ObjectOutputStream bos=new ObjectOutputStream(fos);
bos.writeObject(ca);
bos.flush();
bos.close();
FileInputStream fis=new FileInputStream(f1);
ObjectInputStream bis=new ObjectInputStream(fis);
Cat caca=(Cat)bis.readObject();
bis.close();
System.out.println("aa");
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
}
}
class Cat implements Serializable{
private int weight=0;
private String name=null;
Cat(int w, String n){
weight=w;
name=n;
}
int getWeight(){
return weight;
}
public String toString(){
return "I am cat "+name;
}
}}这段代码抛异常:NotSerializableException
我已经实现了这个接口,
怎么还有这种异常啊?
File f1=new File("f:\\touch.txt");
Cat ca=new Test().new Cat(20,"Lucy");
try{
FileOutputStream fos=new FileOutputStream(f1);
ObjectOutputStream bos=new ObjectOutputStream(fos);
bos.writeObject(ca);
bos.flush();
bos.close();
FileInputStream fis=new FileInputStream(f1);
ObjectInputStream bis=new ObjectInputStream(fis);
Cat caca=(Cat)bis.readObject();
bis.close();
System.out.println("aa");
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
}
}
class Cat implements Serializable{
private int weight=0;
private String name=null;
Cat(int w, String n){
weight=w;
name=n;
}
int getWeight(){
return weight;
}
public String toString(){
return "I am cat "+name;
}
}}这段代码抛异常:NotSerializableException
我已经实现了这个接口,
怎么还有这种异常啊?
问题解决了!哪位达人帮忙分析下原因.
这句话太迥异了。。我没见过这么new的
public class Test {
改为
public class Test implements Serializable {
运行就没问题了
原因未知,感觉和Cat是内部类有关,
Cat是Test的内部类,所以Test也要实现Serializable接口