首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java相关 >

为啥输出是null

2013-04-09 
为什么输出是nullpackage Externalizableimport java.io.Externalizableimport java.io.IOExceptionimp

为什么输出是null
package Externalizable;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Person implements Externalizable {

private String name;
private int age;
public Person(){

}

public Person(String name,  int age){
this.name = name;
this.age = age;
}

public String toString(){
return "姓名: " +this.name + " 年龄" + this.age;
}
//只写或读 下面的东西
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(this.name);
out.writeObject(age);
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
this.name = (String)in.readObject();
this.age = in.readInt();
}
}
-----------------------------------------------
package Externalizable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import Transirnt.Person;

public class Externalizabletest {

public static void main(String[] args) {

ser();
dser();

}

private static void ser() {

File f = new File("e:/" + File.separator + "tes.txt");
try {
ObjectOutputStream oos = null;
OutputStream out = new FileOutputStream(f);
oos = new ObjectOutputStream(out);
oos.writeObject(new Person("lkkj", 12));
//System.out.println();
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

private static void dser() {
try {
File f = new File("e:/" + File.separator + "tes.txt");
ObjectInputStream ois = null;
InputStream input = new FileInputStream(f);
ois = new ObjectInputStream(input);
Object obj = ois.readObject();
ois.close();
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

}
}
求大神帮助。。。为啥输出是null
[解决办法]
楼主的代码测试了一下
public class Person implements Serializable{
这里改一下
存入的时候稍微修改了一下
这样就能读取和存储了.


private static void ser() {
FileOutputStream fos = null;
try {
//Person p=new Person("leilei", 12);
T t=new T();
t.k=100;
fos = new FileOutputStream("D://tes.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);


oos.writeObject(t);
oos.flush();
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}


[解决办法]
Person要实现Serializable接口,另外提示EOFException,你又实现了Externalizable接口的方法,两次读,造成文件结尾了还继续读文件。若你想序列化写入数据,不需要实现Externalizable接口。

热点排行