1、ObjectInputStream() 的readObject()用于读入对象
ObjectOutputStream() 的writeObject()用于写入对象
那么请问怎么修改文件里的对象呢?
比如说文件“student.dat” 里有个对象stu; 我怎么能修改stu.name 的值呢?
2、加入student.dat 是个空文件
FileInputStream file = new FileInputStream(student.dat);
ObjectInputStream in = new ObjectInputStream(file);
stu = in.readObject();会返回null还是怎样? 我运行了一下抛出IOException 了~
谢谢大虾们了~~~
ObjectOutputStream() 的writeObject()用于写入对象
那么请问怎么修改文件里的对象呢?
比如说文件“student.dat” 里有个对象stu; 我怎么能修改stu.name 的值呢?
2、加入student.dat 是个空文件
FileInputStream file = new FileInputStream(student.dat);
ObjectInputStream in = new ObjectInputStream(file);
stu = in.readObject();会返回null还是怎样? 我运行了一下抛出IOException 了~
谢谢大虾们了~~~
2, FileInputStream file = new FileInputStream("student.dat");
空文件你为什么要读啊?读空文件返回IOException我感觉很正常哦……
它保存的是一个对象整体,而且也有它自己的保存格式
2、先判断file.available()是否等于0
import java.io.*;
import java.util.*;class Data implements Serializable { // 实现序列话接口
private int n; public Data(int n) {
this.n = n;
} public int getN() {
return n;
} public void setN(int n) {
this.n = n;
} public String toString() {
return Integer.toString(n);
}
}class Worm implements Serializable {
private static final long serialVersionUID = -935278024637286504L; public static void main(String[] args) throws ClassNotFoundException,
IOException { // 序列话读入和写入Object可能会有这两个异常
// 将你要序列化的object,保留到一个文件中
Random rand = new Random();
Data d = new Data(rand.nextInt(10)); // 构建你需要序列话的Object
System.out.println("d = " + d);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
"c:\\worm.out")); // 准备写入的文件
out.writeObject(d);
out.flush();
out.close(); // 执行到这里你可以看见worm.out这个文件,
// 以下的代码读出你刚刚写入Object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"c:\\worm.out")); // 读你刚刚写入的文件
Data d2 = (Data) in.readObject(); // 重新构建你刚刚写入的Object
System.out.println("d2 = " + d2);
}
}
大侠能给个将DATA读出,改,然后写回的代码么?谢谢!!!!!
我不懂的是,用ObjectInputStream只能读不能改的吧?而用ObjectOutputStream只能写不能读?
那么怎么改啊~我对文件流还没完整弄明白!谢谢大侠指教!
"c:\\worm.out")); // 读你刚刚写入的文件
Data d2 = (Data) in.readObject(); // 重新构建你刚刚写入的Object这样不是读出一个对象了吗?
然后对这个对象进行操作
d2.××();
这样不就能对 对象操作了吗
然后把该对象写进去不就OK了吗
我是怕按你的方法写回去的时候会不会文件里有2个d2了,一个修改前的一个修改后的。
问个问题:
如果文件“1.dat”里存了两个类d1,d2
d3 = readObject();
writeObject(d4);
后“1.dat”里存的是d1,d4 还是d1,d2,d4 ???