java 输出到文件尾_求助关于ObjectOutputStream在文件末尾多次追加写入对象的问题...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

import java.io.*;

class Person implements Serializable{

private String username;

private int password;

public Person(String username, int password) {

this.username = username;

this.password = password;

}

@Override

public String toString() {

return "Person{" +

"username='" + username + '\'' +

", password=" + password +

'}';

}

}

public class Main {

public static void main(String args[]) throws Exception{

Person per[] = {new Person("qwe",80),new Person("weq",15),new Person("ewq",16)};

MyObjectOutputStream.ser(per);

Object obj[] = dser();

for(int i=0;i

Person p = (Person)obj[i];

System.out.println(p);

}

}

public static class MyObjectOutputStream extends ObjectOutputStream{

public MyObjectOutputStream(OutputStream os) throws IOException {

super(os);

}

protected void writeStreamHeader() throws IOException{

super.reset();

}

public static void ser(Object obj) throws Exception{

File f = new File("D:"+ File.separator+"test.txt");

if(!f.exists()){

f.createNewFile();

}

FileOutputStream fos = new FileOutputStream(f,true);

ObjectOutputStream oos = null;

if(f.length() == 0){

oos = new ObjectOutputStream(fos);

}

else {

System.out.println("111111111111111111");

oos = new MyObjectOutputStream(fos);

}

oos.writeObject(obj);

oos.close();

}

}

public static Object[] dser() throws Exception{

File f = new File("D:"+ File.separator+"test.txt");

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));

Object obj[] = (Object[])ois.readObject();

ois.close();

return obj;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值