62,625
社区成员
发帖
与我相关
我的任务
分享
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.Files;
import static java.nio.file.StandardOpenOption.*;
public class Test{
public static void main(String[] args){
writeObject();
readObject();
}
private static void writeObject(){
Student student = new Student(123,"张三",200502);
HashMap<String,Integer> scores = new HashMap<>();
scores.put("java",96);
scores.put("c++",86);
scores.put("C#",90);
try(ObjectOutputStream out = new ObjectOutputStream(
Files.newOutputStream(path,CREATE,WRITE));){
out.writeObject(student);
out.writeObject(scores);
}catch(IOException e){
e.printStackTrace();
System.exit(1);
}
}
@SuppressWarnings("unchecked")
private static void readObject(){
try(ObjectInputStream in = new ObjectInputStream(
Files.newInputStream(path,READ));){
Student student = (Student)(in.readObject());
HashMap<String,Integer> scores = (HashMap<String,Integer>)(in.readObject());
System.out.println(student);
Set<String> keySet = scores.keySet();
Iterator<String> courses = keySet.iterator();
String course = null;
int score = 0;
while(courses.hasNext()){
course = courses.next();
score = scores.get(course);
System.out.printf("[%s:%d]",course,score);
}
}catch(IOException|ClassNotFoundException e){
e.printStackTrace();
System.exit(1);
}
}
private static Path path = Paths.get(System.getProperty("user.dir")).resolve("studentInfo.bin");
}
class Student implements Serializable{
private static final long serialVersionUID = 1L;
public Student(int sno,String name,int id){
this.sno = sno;
this.name = name;
this.id = id;
}
@Override
public String toString(){
return String.format("Student[sno:%d,name:%s,id:%d]",sno,name,id);
}
private int sno;
private String name;
private int id;
}