تا به حال به این دو کلمه در زبان جاوا برخوردید و کاربرد آن را میدانید
گاهی اوقات بیش میباد که احتیاج به ذخیره یک شی به صورت فایل است تا بعدا همون شی را بتون بازیابی کرد
مثال زیر این امر را تفهیم میکنه
How to write an Object to file in Java
1. Address.java
Create an “Address” object and implement Serializable interface. This object is going to write into a file.
package com.j2eelist.io; import java.io.Serializable; public class Address implements Serializable{ String street; String country; public void setStreet(String street){ this.street = street; } public void setCountry(String country){ this.country = country; } public String getStreet(){ return this.street; } public String getCountry(){ return this.country; } @Override public String toString() { return new StringBuffer(" Street : ") .append(this.street) .append(" Country : ") .append(this.country).toString(); } }
2. Serializer.java
This class will write the “Address” object and it’s variable value (“wall street”, “united state”) into a file named “address.ser”, locate in c drive.
package com.j2eelist.io; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class Serializer { public static void main (String args[]) { Serializer serializer = new Serializer(); serializer.serializeAddress("wall street", "united state"); } public void serializeAddress(String street, String country){ Address address = new Address(); address.setStreet(street); address.setCountry(country); try{ FileOutputStream fout = new FileOutputStream("c:\\address.ser"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(address); oos.close(); System.out.println("Done"); }catch(Exception ex){ ex.printStackTrace(); } } }