搜索
您的当前位置:首页正文

Java中对象追加的问题

来源:易榕旅网
Java中对象追加的问题

package com.bd.io; import java.io.File;

import java.io.IOException;

import java.io.ObjectOutputStream; import java.io.OutputStream; /**

* 此类继承ObjectOutputStream,重写writeStreamHeader()方法,以实现追加写入时去掉头部信息 */

public class MyObjectOutputStream extends ObjectOutputStream { // writeStreamHeader()方法是在ObjectOutputStream的构造方法里调用的 // 由于覆盖后的writeStreamHeader()方法用到了f。如果直接用此构造方法创建 // 一个MyObjectOutputStream对象,那么writeStreamHeader()中的f是空指针 // 因为f还没有初始化。所以这里采用单态模式 public MyObjectOutputStream(OutputStream out) throws IOException, SecurityException { super(out); } MyObjectOutputStream() throws IOException, SecurityException { super(); } // 返回一个MyObjectOutputStream对象,这里保证了new MyObjectOutputStream(out, f) // 之前f已经指向一个File对象 @Override protected void writeStreamHeader() throws IOException { // 文件不存在或文件为空,此时是第一次写入文件,所以要把头部信息写入。 } }

package com.bd.io;

import java.io.Serializable;

public class Dog implements Serializable {

private String name;

}

private int age;

public Dog(String name, int age) { }

public String getName() { }

public void setName(String name) { }

public int getAge() { }

public void setAge(int age) { }

public void print(){ }

System.out.println(name + \"|\" + age); this.age = age; return age; this.name = name; return name; super();

this.name = name; this.age = age;

package com.bd.io;

import java.io.*;

import java.util.ArrayList; import java.util.Calendar; import java.util.List;

public class InputDog { public static void out(File path, Dog dog) { ObjectOutputStream out = null; try { if (path.exists()) { out = new MyObjectOutputStream(new FileOutputStream(path, true));

}

} else { out = new ObjectOutputStream(new FileOutputStream(path, true)); }

out.writeObject(dog); out.writeObject(dog);

} catch (Exception ex) { ex.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } }

public static void in(String path) { ObjectInputStream in = null; try { in = new ObjectInputStream(new FileInputStream(path)); while (true) { Dog dog = (Dog) in.readObject(); System.out.println(dog.getName()); } } catch (EOFException e) { } catch (Exception ex) { ex.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } }

public static void main(String[] args) { ObjectInputStream in = null; List list = new ArrayList(); list.add(new Dog(\"aa\ list.add(new Dog(\"bb\ list.add(new Dog(\"cc\ list.add(new Dog(\"dd\

}

}

String path = \"d://abc\"; File file = new File(path); // File path

// out(path, new Dog(\"aa\out(file, new Dog(\"bb\out(file, new Dog(\"cc\out(file, new Dog(\"dd\in(path);

因篇幅问题不能全部显示,请点此查看更多更全内容

Top