JAVA串行化问题~~~ 对象保存在文件中怎么删除这个对象(请看代码)
以下代代码把对象存如了文件中
Customer cust = new Customer( "张三 ", "00001 ", "1234 ", 30000); //第一个对象写入了文件中
10 objectOut.writeObject(cust);
11 cust = new Customer( "李四 ", "00002 ", "5678 ", 10000); //第二个对象写入了文件
12 objectOut.writeObject(cust);
问题: 怎么样从文件中删除和修改所存入的对象信息
例如: 我想从文件中删除第李四这条对象记录,如何实现?
我想更改李四着条记录的00002该为99999如和实现?
//////////////////////////////////////////////////////////////////////////////////
import java.io.*;
2
3public class ObjectIODemo {
4 public static void main(String[] args) {
5 try {
6 ObjectOutputStream objectOut = new ObjectOutputStream
7 (new BufferedOutputStream(new FileOutputStream( "object.bin ")));
8
9 Customer cust = new Customer( "张三 ", "00001 ", "1234 ", 30000); //第一个对象写入了文件中
10 objectOut.writeObject(cust);
11 cust = new Customer( "李四 ", "00002 ", "5678 ", 10000); //第二个对象写入了文件
12 objectOut.writeObject(cust);
13 objectOut.close();
14
15 ObjectInputStream objectIn = new ObjectInputStream
16 (new BufferedInputStream(new FileInputStream( "object.bin ")));
17
18 cust = (Customer)objectIn.readObject();
19 display(cust);
20
21 cust = (Customer)objectIn.readObject();
22 display(cust);
23
24 objectIn.close();
25 }
26 catch(NotSerializableException e) {
27 System.out.println(e.getMessage());
28 }
29 catch(
ClassNotFoundException e) {
30 System.out.println(e.getMessage());
31 }
32 catch(
IOException e) {
33 System.out.println(e.getMessage());
34 }
35 }
36
37 private static void display(Customer cust) {
38 System.out.println( "Name: " cust.getName());
39 System.out.println( "ID: " cust.getID());
40 System.out.println( "Password: " cust.getPassword());
41 System.out.println( "Balance: " cust.getBalance());
42 }
43}
44
------解决方案--------------------先全部读出来,再把文件删掉重新创建
------解决方案--------------------字段的长度固定吗,如果固定可以根据记录在数据苦的位置直接定位,然后用randomaccessfile打开文件,用seek定位,然后进行记录的修改