求写个java的小程序。谢谢!

2024-11-25 12:19:47
推荐回答(2个)
回答1:

这个简单,网上也有相关的例子,关于ObjectOutputStream的用法
package objs;
import java.io.Serializable;
public class Carplate implements Serializable {
private static final long serialVersionUID = -6670528088216041285L;

private String number;
private String state;
private String color;

public Carplate(String pNum,String pState,String pColor){
this.number=pNum;
this.state=pState;
this.color=pColor;
}

public String toString(){
return "number:"+this.state+",state:"+state+",color:"+color;
}

}

//===============================================
package objs;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class CarplateTest {
public static void main(String[] args){
Carplate carp1=new Carplate("A123","on","黑色");
Carplate carp2=new Carplate("B888","off","白色");
Carplate carp3=new Carplate("C666","off","蓝色");

ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("D:\\tool lib\\data.txt"));
oos.writeObject(carp1);
oos.writeObject(carp2);
oos.writeObject(carp3);

carp1 = null;
carp2 = null;
carp3 = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
oos = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}

// 把对象从文件读入.
ObjectInputStream ois = null;
int objCount=0;
try {
ois = new ObjectInputStream(new FileInputStream("D:\\tool lib\\data.txt"));

while(true){
// 输出从文件中读取到的学生的信息, 用于查检是否正确
Carplate aCarp=(Carplate) ois.readObject();
objCount++;
System.out.println(aCarp.toString());
}
}catch(EOFException eofe){
System.out.println("对象读取完成!");
}catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
System.out.println("对象个数:"+objCount);
if (ois != null) {
try {
ois.close();
ois = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

回答2:

the number of objects可以理解为对象的个数,而不是对象的号。
也就是说文件里不一定只有三个对象,所以,要你自己检测到文件末尾,才会有EOFException。