把对象按这种格式进行序列化,以下的代码不知到哪里有不对的地方??
目标格式为::
姓名: 科目一 科目二 科目三
张三 34 45 89
李四 89 06 90
对象实体已经定义好了!
package cn.itcast.heima;
import java.io.IOException;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class Student implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private int subject1;
private int subject2;
private int subject3;
public Student(String name) {
super();
this.name = name;
}
private int total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
public int getTotal() {
total = subject1 + subject2 + subject3;
return total;
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
System.out.println("我被调用了");
}
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
System.out.println("我被调用了");
String info = name + " " + subject1 + " " + subject3 + " "
+ subject2 + " " + total;
stream.writeChars(info);
stream.flush();
}
@SuppressWarnings("unused")
private void readObjectNoData() throws ObjectStreamException {
}
}
以下是调用代码!
package cn.itcast.heima;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Demo3 {
public static void main(String[] args) throws IOException {
String path=Demo3.class
.getClassLoader().getResource("stu.txt").getPath().substring(0, Demo3.class
.getClassLoader().getResource("stu.txt").getPath().lastIndexOf("/")-3)+"src/stu.txt";
System.out.println(path);
FileOutputStream fos = new FileOutputStream(path);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Student stu = new Student("张三");
stu.setSubject1(11);
stu.setSubject2(22);
stu.setSubject3(33);
oos.writeObject(stu);
oos.close();
}
}
|