






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







Serialization
Ali,defence,9201211Usman,gulberg, Salman,LUMS,
……………………… FileReader fr = new FileReader("persons.txt");BufferedReader br = new BufferedReader(fr); String line = br.readLine(); while ( line != null ) { tokens = line.split(","); name = tokens[0];add = tokens[1]; ph = tokens[2]; PersonInfo p = new PersonInfo(name, add, ph);
PersonInfo p = new PersonInfo( ); ObejctOutputStream out; // out.writeObject(p); writing PersonInfo’s object p
ObejctInputStream in; // reading PersonInfo’s object. Remember type casting //PersonInfo is required obj = (PersonInfo)in.readObject( );
Example Code 22.1: Reading / Writing PersonInfo objects
import import (^) javax.swing.; java.io. class PersonInfo implements Serializable { String name; StringString address;phoneNum;
//parameterized constructor public PresonInfo(String n, String a, String p) { nameaddress = n; = a; phoneNm = p; } //methodpublic void for printPersonInfo(displaying person ) record{ on GUI JOptionPane.showMessageDialog(null , “name: ” + name + “address:” +address + “phone no:” + phoneNum); } } // end class
import java.io*; public class ReadEx{ public static void main(String args[ ]){ try { // attaching FileInput stream with “ali.dat” FileInputStream fin = new FileInputStream("ali.dat"); // attaching FileInput stream over ObjectInput stream ObjectInputStream in = new ObjectInputStream(fis); //de-serialization// reading object from ‘ali.dat’ PersonInfo pRead = (PersoInfo)in.ReadObject( ); //// callingobject containsprintPersonInfo same set method of values to confirm before that // serializatoion pRead.printPersonInfo(); //in.close(); closing streams fis.close(); } catch (Exception ex){ System.out.println(ex) } } // end class
Object Serialization & Network
import java.net.; importimport java.io.;javax.swing.; public class ServerReadNetEx{ public static void main(String args[]){ try { // create a server socket ServerSocket ss = new ServerSocket(2222); System.out.println("Server started..."); / (^) socketLoop back and towait the for accept a new method connection of the request. server So */ server^ will^ continuously^ listen^ for^ requests while(true) { // wait for incoming connection Socket s = ss.accept(); System.out.println("connection request recieved"); // Get I/O streams InputStream is = s.getInputStream(); // attaching ObjectOutput stream over Input stream ObjectInputStream ois = new ObjectInputStream(is); // read PersonInfo object from network PersonInfo p = (PersonInfo)ois.read( ); p.printPersonInfo(); //s.close(); closing communication socket } // end while
}catch(Exception ex){ System.out.println(ex); } } } // end class