为什么输出是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 (Class
NotFoundException e) {
e.printStackTrace();
}
}
}
求大神帮助。。。
------解决方案--------------------楼主的代码测试了一下
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);