为什么输出是null

ljs34101130 2013-03-13 12:08:08
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();
}

}
}
求大神帮助。。。
...全文
122 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
yanxing2012 2013-03-13
  • 打赏
  • 举报
回复
Person要实现Serializable接口,另外提示EOFException,你又实现了Externalizable接口的方法,两次读,造成文件结尾了还继续读文件。若你想序列化写入数据,不需要实现Externalizable接口。
大海之粟 2013-03-13
  • 打赏
  • 举报
回复
楼上正解,直接写对象就可以了
失落夏天 2013-03-13
  • 打赏
  • 举报
回复
楼主的代码测试了一下 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();
		}
	}
yyw6637 2013-03-13
  • 打赏
  • 举报
回复
LZ你敢不敢把错误信息帖出来

50,528

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧