您的位置:首页 > 其它

序列化和反序列化的例子 程序中新建文件的操作

2014-07-23 07:43 225 查看
public class Serialization {

Logger logger = LoggerFactory.getLogger(Serialization.class);
String filePath = "serialization/";
File folder = new File(filePath);

public static void main(String[] args) throws IOException, ClassNotFoundException {
Serialization serialization = new Serialization();
serialization.save();
serialization.restore();

}

private void restore() throws IOException, ClassNotFoundException {
File file = new File(folder,"a.txt");
FileInputStream inputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Person person = (Person) objectInputStream.readObject();
System.out.println(person.getName());

}

private void save() {
Person tom = new Person("jim", 34);
if (!folder.exists()) {
folder.mkdir();
}
File file = new File(folder,"a.txt");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(tom);
objectOutputStream.flush();
objectOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐