当前位置: 移动技术网 > IT编程>开发语言>Java > java 对象输入输出流读写文件的操作实例

java 对象输入输出流读写文件的操作实例

2019年07月19日  | 移动技术网IT编程  | 我要评论

java 对象输入输出流读写文件的操作实例

java 支持对对象的读写操作,所操作的对象必须实现serializable接口。

实例代码:

package vo; 
 
import java.io.serializable; 
 
public class animal implements serializable { 
  private static final long serialversionuid = 1l; 
  private string name; 
  private integer weight; 
  private string color; 
  private string type; 
  private integer age; 
  private integer lifetime; 
  public string getname() { 
    return name; 
  } 
  public void setname(string name) { 
    this.name = name; 
  } 
  public integer getweight() { 
    return weight; 
  } 
  public void setweight(integer weight) { 
    this.weight = weight; 
  } 
  public string getcolor() { 
    return color; 
  } 
  public void setcolor(string color) { 
    this.color = color; 
  } 
  public string gettype() { 
    return type; 
  } 
  public void settype(string type) { 
    this.type = type; 
  } 
  public integer getage() { 
    return age; 
  } 
  public void setage(integer age) { 
    this.age = age; 
  } 
  public integer getlifetime() { 
    return lifetime; 
  } 
  public void setlifetime(integer lifetime) { 
    this.lifetime = lifetime; 
  } 
  public animal(string name, integer weight, string color, string type, integer age, integer lifetime) { 
    super(); 
    this.name = name; 
    this.weight = weight; 
    this.color = color; 
    this.type = type; 
    this.age = age; 
    this.lifetime = lifetime; 
  } 
  @override 
  public string tostring() { 
    return "animal [name=" + name + ", weight=" + weight + ", color=" + color + ", type=" + type + ", age=" + age + ", lifetime=" + lifetime + "]"; 
  } 
   
} 

package objectstream; 
 
import java.io.file; 
import java.io.fileinputstream; 
import java.io.fileoutputstream; 
import java.io.objectinputstream; 
import java.io.objectoutputstream; 
 
import vo.animal; 
 
public class testobjectstream { 
  public static void main(string[] args) { 
    try { 
      objectoutputstream oos = new objectoutputstream(new fileoutputstream(new file("d:/oos.dat"))); 
      animal a1 = new animal("tiger", 120, "red", "cat", 12, 20); 
      animal a2 = new animal("eagle", 10, "gold", "bird", 6, 10); 
      oos.writeobject(a1); 
      oos.writeobject(a2); 
      oos.flush(); 
      oos.close(); 
       
      objectinputstream ois = new objectinputstream(new fileinputstream("d:/oos.dat")); 
      animal ra1 = (animal) ois.readobject(); 
      system.out.println(ra1.tostring()); 
      animal ra2 = (animal) ois.readobject(); 
      system.out.println(ra2.tostring()); 
    } catch (exception e) { 
      e.printstacktrace(); 
    } 
  } 
} 

输出结果:

animal [name=tiger, weight=120, color=red, type=cat, age=12, lifetime=20] 
animal [name=eagle, weight=10, color=gold, type=bird, age=6, lifetime=10] 

如有疑问请留言或者到本站社区交流讨论,本站关于java开发的文章还有很多,希望大家搜索查阅,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网