@XQF
2017-02-16T09:57:12.000000Z
字数 1786
阅读 1492
java
class Student implements Serializable {private String name;private int age;public Student(String name, int age) {this.name = name;this.age = age;}public String toString() {return "name :" + name + " " + "age :" + age;}}public class Test {public static void main(String[] args) {File file = new File("src/com/leetcode/xqf/hah.txt");FileInputStream fileIn = null;try {fileIn = new FileInputStream(file);FileOutputStream fileOut = new FileOutputStream(file);ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);objectOut.writeObject(new Student("XQF", 23));objectOut.writeObject(new Student("WLY", 20));ObjectInputStream objectIn = new ObjectInputStream(fileIn);Student s1 = (Student) objectIn.readObject();System.out.println(s1);Student s2 = (Student) objectIn.readObject();System.out.println(s2);} catch (FileNotFoundException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}
ublic class Serializable01 extends Object implements Serializable{private static final long serialVersionUID = -1466479389299512377L;public byte b = 12;public byte getB() {return b;}public void setB(byte b) {this.b = b;}public static void main(String[] args) {try {FileOutputStream fos = new FileOutputStream(new File("E:\\tmp\\demo2.txt"));ObjectOutputStream os = new ObjectOutputStream(fos);Serializable01 s = new Serializable01();os.writeObject(s);os.flush();os.close();FileInputStream fis = new FileInputStream(new File("E:\\tmp\\demo2.txt"));ObjectInputStream ois = new ObjectInputStream(fis);Serializable01 s2 = (Serializable01)ois.readObject();System.out.println(s2.getB());ois.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}}}
