can4ec, не надо повторять вопрос по несколько раз. Когда у меня будет время, тогда я и напишу ответ. | Код | import java.io.*; import java.util.*;
public class SerializeTest { public static void write(int number, File file) { try { for(int i = 0; i < number; i++) { ComplexType object = new ComplexType(); ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file, true))); out.writeObject(object); out.close(); } } catch(IOException e) { e.printStackTrace(); } }
public static List<ComplexType> read(File file) { ArrayList<ComplexType> list = new ArrayList<ComplexType>(); try { NonClosableInputStream nonClosableInputStream = new NonClosableInputStream(new BufferedInputStream(new FileInputStream(file))); while(nonClosableInputStream.available() > 0) { try { ObjectInputStream in = new ObjectInputStream(nonClosableInputStream); list.add((ComplexType) in.readObject()); in.close(); } catch(ClassNotFoundException e) { e.printStackTrace(); } } nonClosableInputStream.realyClose(); } catch(IOException e) { e.printStackTrace(); } return list; }
public static void main(String[] args) throws IOException { File file = File.createTempFile("test-", ".ser"); file.deleteOnExit(); write(10, file); List<ComplexType> list = read(file); System.out.println(list); }
public static class ComplexType implements Serializable { public String text; public int x, y; public Date date;
public ComplexType() { date = new Date(); text = date.toString(); x = y = 0; }
@Override public String toString() { return getClass().getSimpleName() + "{" + text + "}"; } }
private static class NonClosableInputStream extends InputStream { private InputStream delegate;
public NonClosableInputStream(InputStream delegate) { this.delegate = delegate; }
public int read() throws IOException { return delegate.read(); }
public int read(byte[] b) throws IOException { return delegate.read(b); }
public int read(byte[] b, int off, int len) throws IOException { return delegate.read(b, off, len); }
public long skip(long n) throws IOException { return delegate.skip(n); }
public int available() throws IOException { return delegate.available(); }
public void close() { }
public void realyClose() throws IOException { delegate.close(); }
public void mark(int readlimit) { delegate.mark(readlimit); }
public void reset() throws IOException { delegate.reset(); }
public boolean markSupported() { return delegate.markSupported(); } } } |
--------------------
Disclaimer: this post contains explicit depictions of personal opinion. So, if it sounds sarcastic, don't take it seriously. If it sounds dangerous, do not try this at home or at all. And if it offends you, just don't read it.
|