java对象写入文件_java使用ObjectOutputStream将对象写入到文件

2014-02-24 06:30:02

阅读( 772 )

下面是要写入类Person的定义,此类需要实现Serializable接口

import java.io.Serializable;

/**

*

* @author outofmemory.cn

*/

public class Person implements Serializable {

private String firstName;

private String lastName;

private int age;

/**

* Creates a new instance of Person

*/

public Person() {

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

//Overriding toString to be able to print out the object in a readable way

//when it is later read from the file.

public String toString() {

StringBuffer buffer = new StringBuffer();

buffer.append(firstName);

buffer.append("\n");

buffer.append(lastName);

buffer.append("\n");

buffer.append(age);

buffer.append("\n");

return buffer.toString();

}

}

下面代码使用ObjectOutputStream将对象写入到文件:

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;

/**

*

* @author outofmemory.cn

*/

public class Main {

/**

* Example method for using the ObjectOutputStream class

*/

public void writePersons(String filename) {

ObjectOutputStream outputStream = null;

try {

//Construct the LineNumberReader object

outputStream = new ObjectOutputStream(new FileOutputStream(filename));

Person person = new Person();

person.setFirstName("James");

person.setLastName("Ryan");

person.setAge(19);

outputStream.writeObject(person);

person = new Person();

person.setFirstName("Obi-wan");

person.setLastName("Kenobi");

person.setAge(30);

outputStream.writeObject(person);

} catch (FileNotFoundException ex) {

ex.printStackTrace();

} catch (IOException ex) {

ex.printStackTrace();

} finally {

//Close the ObjectOutputStream

try {

if (outputStream != null) {

outputStream.flush();

outputStream.close();

}

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

new Main().writePersons("myFile.txt");

}

}

分享给朋友:

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息:

面试题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值