public class Test {
/**
* @param args
* @throws UnknownHostException
* @throws SocketException
*/
public static void main(String[] args){
try {
File f=new File("abc.txt");
FileOutputStream fos=new FileOutputStream(f);
ObjectOutputStream out=new ObjectOutputStream(fos);
out.writeObject(new Point(3,4));//怎么改成添加在文件尾?
out.writeObject(new Point(2,3));//怎么改成添加在文件尾?
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ObjectInputStream in=new ObjectInputStream(new FileInputStream(new File("abc.txt")));
int i=0;
while(true){
try{
Point p=(Point)in.readObject();
System.out.println(p);
}
catch(EOFException e){
break;
}
Point p=(Point)in.readObject();
System.out.println(p);
}
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Point implements Serializable{
private int x;
private int y;
public Point(){
}
public Point(int x,int y){
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "x="+x+",y="+y;
}
}
当程序第一次运行时,abc.txt写入了两个对象。可再次运行,打印出的还是两个对象。怎么写才是添加到文件中的?
如:
第一次运行结果:
x=3,y=4
x=2,y=3
第二次运行结果:
x=3,y=4
x=2,y=3
x=3,y=4
x=2,y=3
|