SlideShare ist ein Scribd-Unternehmen logo
1 von 11
Downloaden Sie, um offline zu lesen
Lecture 12
Serializable Interface




              Object Oriented Programming
              Eastern University, Dhaka
                      Md. Raihan Kibria
What is serialization?
   Example: we want to store an object on the
    disk and recover later
public class SerializableDemo implements Serializable {

Integer id;
String name;
String address;

public static void main(String[] args) {

SerializableDemo s = new SerializableDemo();
s.id= new Integer(9);
s.name = "John";
s.address = "34 Road, Dhanmondi";

//writing
File f = new File("/home/user/eu/oop/SerializableDemo.ser");
try{              Rest of the code
  ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(f));
     o.writeObject(s);
     o.close();
  }catch(Exception e){
     e.printStackTrace();
     System.exit(0);
}

//reading
try{
  ObjectInputStream i = new ObjectInputStream(new FileInputStream(f));
  SerializableDemo d = (SerializableDemo)i.readObject();
  i.close();
  System.out.println(d.id);
  System.out.println(d.name);
  System.out.println(d.address);
}catch(Exception e){
  e.printStackTrace();
}
}
}
Output
         9
         John
         34 Road, Dhanmondi




Lesson learned: we can save an object and retrieve if later if
implement java.io.Serializable interface
Another serializable demo
public class SerializableDemo2 extends JFrame{

    SerializableDemo2(){
      this.setBounds(100, 100, 400, 300);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.add(new JButton("Test button"));
    }

    public static void main(String[] args) {
      SerializableDemo2 s = new SerializableDemo2();
      s.setVisible(true);
      //writing
      File f = new File("/home/user/eu/oop/SerializableDemo2.ser");

        try{
          ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(f));
          o.writeObject(s);
          o.close();
        }catch(Exception e){
          e.printStackTrace();
          System.exit(0);
        }
    }
}
Output




Also SerializableDemo2.ser file is created in
  the disk
We want to read the serialized
       object by another program

//reading
File f = new File("/home/user/eu/oop/SerializableDemo2.ser");
try{
  ObjectInputStream i = new ObjectInputStream(new FileInputStream(f));
  SerializableDemo2 d = (SerializableDemo2)i.readObject();
  d.setVisible(true);
}catch(Exception e){
  e.printStackTrace();
}


The same frame shows after
reconsructing from serialized
object
Exception handling
try-catch-finally
public class TryCatchDemo {
  public static void main(String[] args) {
    File file = new File("/home/user/tmp");
    FileInputStream fis = null;
    try{
        fis = new FileInputStream(file);
    }catch(FileNotFoundException e){
        System.out.println("The file you are trying to access is not
available");
    }finally{
        try{
            fis.close();
        }catch(Exception ex){
        //nothing to do
        }
    }
  }
}
Details about exceptions

At first code in the try clause is executed
If there is any exception code in Exception
   clause is executed
Finally clause is executed after the try clause
   is executed. We close any resources in the
   finally clause
Finally clause is not mandatory

Exceptions can be extended just time any
 other java class
More on exceptions

If some code in a method raises some
   exception we must handle it either by
   wrapping the code with try-catch block

Alternatively, you can re-raise the exception by
  using throws clause in the method
      public void doSomething(){
        File file = new File("/home/user/a.out");
        FileInputStream fis = null;
        fis = new FileInputStream(file);
      }

      //this code will not compile
throws clause

This will compile; but the caller must handle
 the excepion or declare its own throws

     public void doSomething() throws FileNotFoundException{
       File file = new File("/home/user/a.out");
       FileInputStream fis = null;
       fis = new FileInputStream(file);
     }

Weitere ähnliche Inhalte

Was ist angesagt?

Using the Power to Prove
Using the Power to ProveUsing the Power to Prove
Using the Power to ProveKazuho Oku
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5Tom Corrigan
 
Best practices in Java and Swing
Best practices in Java and SwingBest practices in Java and Swing
Best practices in Java and SwingAshberk
 
First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)Wildan Maulana
 
Unix Programming with Perl 2
Unix Programming with Perl 2Unix Programming with Perl 2
Unix Programming with Perl 2Kazuho Oku
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML SchemaRaji Ghawi
 
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPIPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPGuilherme Blanco
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlHideaki Ohno
 
Controlling Arduino With PHP
Controlling Arduino With PHPControlling Arduino With PHP
Controlling Arduino With PHPThomas Weinert
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMsunng87
 
The Ring programming language version 1.9 book - Part 86 of 210
The Ring programming language version 1.9 book - Part 86 of 210The Ring programming language version 1.9 book - Part 86 of 210
The Ring programming language version 1.9 book - Part 86 of 210Mahmoud Samir Fayed
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash scriptSimon Su
 
The Ring programming language version 1.5.1 book - Part 74 of 180
The Ring programming language version 1.5.1 book - Part 74 of 180The Ring programming language version 1.5.1 book - Part 74 of 180
The Ring programming language version 1.5.1 book - Part 74 of 180Mahmoud Samir Fayed
 
system management -shell programming by gaurav raikar
system management -shell programming by gaurav raikarsystem management -shell programming by gaurav raikar
system management -shell programming by gaurav raikarGauravRaikar3
 

Was ist angesagt? (20)

Using the Power to Prove
Using the Power to ProveUsing the Power to Prove
Using the Power to Prove
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5
 
Best practices in Java and Swing
Best practices in Java and SwingBest practices in Java and Swing
Best practices in Java and Swing
 
First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)
 
Shellscripting
ShellscriptingShellscripting
Shellscripting
 
Unix Programming with Perl 2
Unix Programming with Perl 2Unix Programming with Perl 2
Unix Programming with Perl 2
 
Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPIPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
 
Controlling Arduino With PHP
Controlling Arduino With PHPControlling Arduino With PHP
Controlling Arduino With PHP
 
Unix shell scripts
Unix shell scriptsUnix shell scripts
Unix shell scripts
 
PHP7 Presentation
PHP7 PresentationPHP7 Presentation
PHP7 Presentation
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
Clojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVMClojure: Practical functional approach on JVM
Clojure: Practical functional approach on JVM
 
Php arduino
Php arduinoPhp arduino
Php arduino
 
The Ring programming language version 1.9 book - Part 86 of 210
The Ring programming language version 1.9 book - Part 86 of 210The Ring programming language version 1.9 book - Part 86 of 210
The Ring programming language version 1.9 book - Part 86 of 210
 
Hachiojipm11
Hachiojipm11Hachiojipm11
Hachiojipm11
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash script
 
The Ring programming language version 1.5.1 book - Part 74 of 180
The Ring programming language version 1.5.1 book - Part 74 of 180The Ring programming language version 1.5.1 book - Part 74 of 180
The Ring programming language version 1.5.1 book - Part 74 of 180
 
system management -shell programming by gaurav raikar
system management -shell programming by gaurav raikarsystem management -shell programming by gaurav raikar
system management -shell programming by gaurav raikar
 

Andere mochten auch

Andere mochten auch (9)

Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]
 
Calendario portada
Calendario portadaCalendario portada
Calendario portada
 
Oop lecture6
Oop lecture6Oop lecture6
Oop lecture6
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
 
Oop lecture9 11
Oop lecture9 11Oop lecture9 11
Oop lecture9 11
 
Cwgd
CwgdCwgd
Cwgd
 
Oop lecture2
Oop lecture2Oop lecture2
Oop lecture2
 
Oop lecture1
Oop lecture1Oop lecture1
Oop lecture1
 
Oop lecture8
Oop lecture8Oop lecture8
Oop lecture8
 

Ähnlich wie Serializable Interface Lecture

Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBCPawanMM
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageESUG
 
2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdfrbjain2007
 
Active Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVEActive Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVEkim.mens
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfshahidqamar17
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxRutujaTandalwade
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 

Ähnlich wie Serializable Interface Lecture (20)

Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBC
 
JDBC
JDBCJDBC
JDBC
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
 
Lab4
Lab4Lab4
Lab4
 
Inheritance
InheritanceInheritance
Inheritance
 
2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
Java 7
Java 7Java 7
Java 7
 
Active Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVEActive Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVE
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdf
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
 
Code red SUM
Code red SUMCode red SUM
Code red SUM
 
Bhaloo
BhalooBhaloo
Bhaloo
 
Java 104
Java 104Java 104
Java 104
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
File management
File managementFile management
File management
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 

Mehr von Shahriar Robbani (8)

Group111
Group111Group111
Group111
 
SQL
SQLSQL
SQL
 
Oop lecture9 10
Oop lecture9 10Oop lecture9 10
Oop lecture9 10
 
Oop lecture4
Oop lecture4Oop lecture4
Oop lecture4
 
Oop lecture9
Oop lecture9Oop lecture9
Oop lecture9
 
Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
 
Oop lecture5
Oop lecture5Oop lecture5
Oop lecture5
 
Oop lecture3
Oop lecture3Oop lecture3
Oop lecture3
 

Kürzlich hochgeladen

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...DrVipulVKapoor
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipKarl Donert
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressMaria Paula Aroca
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfChristalin Nelson
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceDr Vijay Vishwakarma
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...Nguyen Thanh Tu Collection
 

Kürzlich hochgeladen (20)

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenship
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian Congress
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdf
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional Intelligence
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
Introduction to Research ,Need for research, Need for design of Experiments, ...
Introduction to Research ,Need for research, Need for design of Experiments, ...Introduction to Research ,Need for research, Need for design of Experiments, ...
Introduction to Research ,Need for research, Need for design of Experiments, ...
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
 

Serializable Interface Lecture

  • 1. Lecture 12 Serializable Interface Object Oriented Programming Eastern University, Dhaka Md. Raihan Kibria
  • 2. What is serialization?  Example: we want to store an object on the disk and recover later public class SerializableDemo implements Serializable { Integer id; String name; String address; public static void main(String[] args) { SerializableDemo s = new SerializableDemo(); s.id= new Integer(9); s.name = "John"; s.address = "34 Road, Dhanmondi"; //writing File f = new File("/home/user/eu/oop/SerializableDemo.ser");
  • 3. try{ Rest of the code ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(f)); o.writeObject(s); o.close(); }catch(Exception e){ e.printStackTrace(); System.exit(0); } //reading try{ ObjectInputStream i = new ObjectInputStream(new FileInputStream(f)); SerializableDemo d = (SerializableDemo)i.readObject(); i.close(); System.out.println(d.id); System.out.println(d.name); System.out.println(d.address); }catch(Exception e){ e.printStackTrace(); } } }
  • 4. Output 9 John 34 Road, Dhanmondi Lesson learned: we can save an object and retrieve if later if implement java.io.Serializable interface
  • 5. Another serializable demo public class SerializableDemo2 extends JFrame{ SerializableDemo2(){ this.setBounds(100, 100, 400, 300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.add(new JButton("Test button")); } public static void main(String[] args) { SerializableDemo2 s = new SerializableDemo2(); s.setVisible(true); //writing File f = new File("/home/user/eu/oop/SerializableDemo2.ser"); try{ ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(f)); o.writeObject(s); o.close(); }catch(Exception e){ e.printStackTrace(); System.exit(0); } } }
  • 6. Output Also SerializableDemo2.ser file is created in the disk
  • 7. We want to read the serialized object by another program //reading File f = new File("/home/user/eu/oop/SerializableDemo2.ser"); try{ ObjectInputStream i = new ObjectInputStream(new FileInputStream(f)); SerializableDemo2 d = (SerializableDemo2)i.readObject(); d.setVisible(true); }catch(Exception e){ e.printStackTrace(); } The same frame shows after reconsructing from serialized object
  • 8. Exception handling try-catch-finally public class TryCatchDemo { public static void main(String[] args) { File file = new File("/home/user/tmp"); FileInputStream fis = null; try{ fis = new FileInputStream(file); }catch(FileNotFoundException e){ System.out.println("The file you are trying to access is not available"); }finally{ try{ fis.close(); }catch(Exception ex){ //nothing to do } } } }
  • 9. Details about exceptions At first code in the try clause is executed If there is any exception code in Exception clause is executed Finally clause is executed after the try clause is executed. We close any resources in the finally clause Finally clause is not mandatory Exceptions can be extended just time any other java class
  • 10. More on exceptions If some code in a method raises some exception we must handle it either by wrapping the code with try-catch block Alternatively, you can re-raise the exception by using throws clause in the method public void doSomething(){ File file = new File("/home/user/a.out"); FileInputStream fis = null; fis = new FileInputStream(file); } //this code will not compile
  • 11. throws clause This will compile; but the caller must handle the excepion or declare its own throws public void doSomething() throws FileNotFoundException{ File file = new File("/home/user/a.out"); FileInputStream fis = null; fis = new FileInputStream(file); }