package com.xuexi.IO; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Obj { public static void main(String[] args) { File file = null; FileOutputStream fos = null; ObjectOutputStream oot = null; FileInputStream fis=null; ObjectInputStream ois =null; User user=null;//需要创建一个User类 接口Serializable 可序化 try{ file = new File("d:\2019.txt"); fos = new FileOutputStream(file); oot = new ObjectOutputStream(fos); user = new User("rose",24,"241251532@qq.com","14251515632"); oot.writeObject(user); fis = new FileInputStream(file); ois = new ObjectInputStream(fis); User user1 = (User)ois.readObject(); System.out.println(user1.getName()+user1.getAge()+user1.getEmanil()+user1.getPhion()); }catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); }finally{ try { fos.flush(); fos.close(); fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.xuexi.IO; import java.io.Serializable; public class User implements Serializable { //User类 String name; int age; String emanil; String phion; public User(String name, int age, String emanil, String phion) { super(); this.name = name; this.age = age; this.emanil = emanil; this.phion = phion; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmanil() { return emanil; } public void setEmanil(String emanil) { this.emanil = emanil; } public String getPhion() { return phion; } public void setPhion(String phion) { this.phion = phion; } }