62,615
社区成员
发帖
与我相关
我的任务
分享
import java.io.Serializable;
import java.io.OutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import static java.nio.file.StandardOpenOption.*;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
public static void main(String[] args){
Person person = new Person("张三",28,"男");
writePeople(person);
readPeople();
}
public Person(String name,int age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString(){
return String.format("person[name:%s,age:%d,sex:%s]",name,age,sex);
}
private static void readPeople(){
try(ObjectInputStream in = new ObjectInputStream(Files.newInputStream(path,READ));){
Person person = null;
for(;;){
person = (Person)(in.readObject());
System.out.println(person);
}
}catch(IOException|ClassNotFoundException e){
System.out.println("All print out");
}
}
private static void writePeople(Person ... people){
ObjectOutputStream file = null;//首次文件不存在.
try{
if(Files.isRegularFile(path)){
file = new MyObjectOutputStream(Files.newOutputStream(path,WRITE,APPEND));
}else{
file = new ObjectOutputStream(Files.newOutputStream(path,CREATE,WRITE,APPEND));
}
for(Person person : people){
file.writeObject(person);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
file.close();
}catch(IOException e){
e.printStackTrace();
System.exit(1);
}
}
}
private int age;
private String name;
private String sex;
private static final Path path = Paths.get(System.getProperty("user.dir")).resolve("people.bin");
}
class MyObjectOutputStream extends ObjectOutputStream{
public MyObjectOutputStream()throws IOException{
super();
}
public MyObjectOutputStream(OutputStream out)throws IOException{
super(out);
}
@Override
public void writeStreamHeader(){
}
}
public class Test7 {
public static void main(String[] args) {
}
}
class Person1 extends ObjectOutputStream {
public Person1() throws IOException {
super();
}
}
class Person2 extends Person1 {
private Person2() throws IOException {
super();
}
public static Person2 p2 = new Person2();
}