实例:
package com.jsu.demo;
import java.io.Serializable;
import java.util.Objects;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return id == student.id && age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age);
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
package com.jsu.demo;
import java.io.*;
public class IODemo {
public static void main(String[] args) {
Object O = reSerializable("D://text//");
Student wp = (Student) O;
System.out.println(wp.getName());
wp.setAge(2000);
System.out.println(wp.getAge());
wp.setAge(18);
}
public static Object reSerializable(String path) {
File file = new File(path);
Object obj = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
obj = ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}finally {
if(ois != null){
try {
ois.close();
}catch (IOException e){
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return obj;
}
public static Object serializable(String path,Object obj){
File file = new File(path);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try{
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
}catch (IOException e){
e.printStackTrace();
}finally {
if(oos != null){
try {
oos.close();
}catch (IOException e){
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return obj;
}
}