Test.java 解决多次写的时候,往往重复写入header,导致读出时,出现streamcorrput异常,所以这里要判断是不是第一次写文件,若是写入头部,否则不写入
这是通过重载writeStreamHeader来实现的
1 package file;
2 import java.io.EOFException;
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.ObjectInputStream;
8 import java.io.ObjectOutputStream;
9 import java.io.Serializable;
10 import java.io.StreamCorruptedException;
11 import java.util.LinkedList;
12 public class Test {
13
14 private static LinkedList al = new LinkedList();
15 public static void main(String[] args) {
16 // TODO Auto-generated method stub
17 System.out.println("welcome!!");
18 try {
19 File file = new File("input.txt");
20 FileOutputStream out = new FileOutputStream(file,true);
21 ObjectOutputStream oo=null;
22 if(file.length()<1)
23 {
24 oo = new ObjectOutputStream(out);
25 }
26 else
27 {
28 oo = new MyObjectOutputStream(out);
29 }
30
31 int i = 0;
32 Node n;
33 while(i++<6)
34 {
35 n = new Node();
36 n.name = "kyle"+i;
37 oo.writeObject(n);
38 }
39 oo.flush();
40 oo.close();
41 FileInputStream in = new FileInputStream("input.txt");
42 ObjectInputStream oi = new ObjectInputStream(in);
43 i = 0;
44
45 while(true)
46 {
47 System.out.println(i++);
48 al.add((Node)oi.readObject());
49 }
50
51 }
52 catch(EOFException es)
53 {
54 return;
55 }
56 catch (Exception e) {
57 // TODO Auto-generated catch block
58 e.printStackTrace();
59
60 }
61 }
62 }
63 class Node implements Serializable
64 {
65 public Node()
66 {
67 name = name+ i++;
68 }
69 public String name;
70 private static int i = 0;
71 public String toString()
72 {
73 return name;
74 }
75 }
76
77
78
79
80
81
MyObjectOutputStream.java
1 package test;
2
3 import java.io.IOException;
4 import java.io.ObjectOutputStream;
5 import java.io.OutputStream;
6
7 public class MyObjectOutputStream extends ObjectOutputStream {
8
9
10 private static boolean flag = true;//判断是否为第一次写入文件
11 private static boolean one = true;
12
13 public MyObjectOutputStream() throws IOException, SecurityException {
14 // TODO Auto-generated constructor stub
24 }
25
26 public MyObjectOutputStream(OutputStream out) throws IOException {
27 super(out);
28 // TODO Auto-generated constructor stub
29 }
30 protected void writeStreamHeader()
31 throws IOException
32 {
33 return; //不写入头部
34 }
35
36 }
37
posted on 2008-04-03 00:43
fullfocus 阅读(1673)
评论(2) 编辑 收藏 所属分类:
JAVA/J2EE