package IOliu; 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 ObjectInputStreamTest { public static void main(String[] args) { File file = null; FileInputStream fis = null; ObjectInputStream ois = null; User user = null; FileOutputStream fos = null; ObjectOutputStream oos = null; try { //保存对象数据到内存中 file = new File("D:\\2017.txt"); fos = new FileOutputStream(file); oos = new ObjectOutputStream(fos); user = new User("Rose",24,"[email protected]","170"); oos.writeObject(user); //从内存中获取对象数据 fis = new FileInputStream(file); ois = new ObjectInputStream(fis); try { User user1 = (User) ois.readObject(); System.out.println(user1.getName()+" "+user1.getAge()+" "+user1.getMail()+" "+user.getHeight()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { oos.flush(); oos.close(); ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package IOliu; import java.io.Serializable; //加接口 对象序列化implements public class User implements Serializable{ private String name; private int age; private String mail; private String height; public User() { super(); } public User(String name, int age, String mail, String height) { super(); this.name = name; this.age = age; this.mail = mail; this.height = height; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } 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 getHeight() { return height; } public void setHeight(String height) { this.height = height; } }
时间: 2024-10-18 18:10:41