[关闭]
@Senl 2017-03-30T04:15:14.000000Z 字数 3085 阅读 1141

3.29学习进度

技术学习


Java

HF Java

序列化(serialization)

Java的输入/输出带有连接类型的串流,它代表来源与目的地之间的连接,连接串流将串流与其他串流连接起来

解序列化(Deseriallization)


序列化和解序列化实例

  1. //Person类
  2. import java.io.*;
  3. public class Person implements Serializable{
  4. private int money; //设置三个私有属性,一个静态变量,一个transient变量测试
  5. private int height;
  6. public String name;
  7. static String Live;
  8. transient String sex;
  9. public void setMoney(int money) {
  10. if(money>0){
  11. this.money = money;
  12. }
  13. }
  14. public void setHeight(int height) {
  15. if(height>0){
  16. this.height = height;
  17. }
  18. }
  19. public void setName(String name) {
  20. this.name = name;
  21. }
  22. public static String getLive() {
  23. return Live;
  24. }
  25. public static void setLive(String live) {
  26. Live = live;
  27. }
  28. public void setSex(String sex) {
  29. this.sex = sex;
  30. }
  31. public void show() {
  32. System.out.println("name:"+name+"money:"+money+"\t"+"height:"+height+"\t");
  33. System.out.println(sex+Live);
  34. }
  35. }
  1. //Person启动类
  2. import java.io.*;
  3. public class CreatePerson {
  4. public static void main(String[] args) {
  5. // TODO Auto-generated method stub
  6. Person boy = new Person(); //创建一个boy为Person类引用对象
  7. boy.setHeight(183); //通过三方法设置boy属性
  8. boy.setMoney(400);
  9. boy.setName("senl");
  10. boy.setSex("male");
  11. Person girl = new Person();//创建一个girl引用为Person类引用变量
  12. girl.setHeight(160);
  13. girl.setMoney(1000000);
  14. girl.setName("yu");
  15. girl.setSex("female");
  16. Person.setLive("yes");
  17. try{ //序列化
  18. FileOutputStream fs = new FileOutputStream("Person.ser");
  19. ObjectOutputStream os = new ObjectOutputStream(fs);
  20. os.writeObject(boy);
  21. os.writeObject(girl);
  22. os.close();
  23. }catch(Exception ex){
  24. ex.printStackTrace();
  25. }
  26. boy =null; //空置引用变量
  27. girl =null;
  28. try { //解序列化
  29. ObjectInputStream is = new
  30. ObjectInputStream(new FileInputStream("Person.ser"));
  31. //转换对象类型
  32. Person boySaved = (Person) is.readObject();
  33. Person girlSaved = (Person)is.readObject();
  34. is.close();
  35. boySaved.show();
  36. girlSaved.show();
  37. } catch(Exception ex) {
  38. ex.printStackTrace();
  39. }
  40. }
  41. }
  1. 测试结果:
  2. name:senlmoney:400 height183
  3. null yes
  4. name:yumoney:1000000 height160
  5. null yes

文件的输入/输出

笔记回顾

简单示例

  1. try{
  2. FileWriter writer = new FileWriter("saved.txt");
  3. writer.writer("hello world");
  4. writer.cloes();
  5. } catch(IOException ex) {
  6. ex.printStackTrace();
  7. }

File类

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注