You are on page 1of 11

Lab Manual for Advanced Computer Programming

Lab-06
Java Filing and Serialization
Lab 6: Java Filing and Serialization

Table of Contents
1. Introduction 55

2. Activity Time boxing 55

3. Objective of the experiment 56

4. Concept Map 56
4.1. Implementing a simple file reader 56
4.1 Serialization 56
4.2 Deserialization 57
4.2.1 Streams to be used 57
4.2.2 Serializable objects: 57

5. Homework before Lab 58


5.1 Problem Solution Modeling 58

6. Procedure& Tools 58
6.1 Tools 58
6.2 Setting-up JDK 1.7 [Expected time = 5mins] 58
6.2.1 Compile and run a Program 58
6.3 Walkthrough Task [Expected time = 30mins] 58
6.3.1 Implementing a simple file reader 58
6.3.2 Serialization 59

7. Practice Tasks 61
7.1 Practice Task 1 [Expected time = 20mins] 61
7.2 Practice Task 2 [Expected time = 20mins] 61
7.3 Practice Task 3 [Expected time = 20mins] 62
7.4 Out comes 62
7.5 Testing 62

8. Evaluation Task (Unseen) [Expected time = 60mins for two tasks] 62

9. Evaluation criteria 62

10. Further Reading 63


10.1 Books 63
10.2 Slides 63

Department of Computer Science, Page 54


C.U.S.T.
Lab 6: Java Filing and Serialization

Lab 6: Java Filing and Serialization

1. Introduction

You have learnt Java constructs, abstract classes and interface, file handling. In this lab, you will
test the theory of storing and retrieving data from files in the form of objects. Youwill
experiment this using serialization.

First important topic that you will study in this lab is the file handling mechanism of Java. Unlike
C++, Java has a very rich library for file handling. Basically Java divides the filing into two
different streams. One is a character stream and the other is byte stream. These both streams have
almost the same functionalities and the major difference is that the character stream reads and
write 16-bit character and on the other hand the byte stream as it is clear from its name can only
read write one byte at a time.

Sometimes, the data contained inside the object is very complex as an object can be composed of
many other complex objects. Java provides a simple alternate to this tedious task using
serialization. Object is represented in bytes format that can be stored and passed to the stream. In
case we need to retrieve the object we can reconstruct it from the saved/stored data stream.
¿ Writing the object is termed serialization or marshaling. Reading back the data into object form
is referred to as deserialization or un-marshaling of data. Objects to be serialized must implement
Serializable interface and the class corresponding to that object must be a public class. Any
attribute of the Serializable class which is non-static and non-transient is preserved. Static data
members are not preserved as they are the property of a class and not the property of the object
and Serialization is all about preserving the state of the object not the class. Transient fields are a
way provided by the serialization mechanism to skip the part of the object that is not relevant or
unimportant.

Relevant Lecture Material

a) Revise Lecture No. 9 and 10


b) Text Book: Java® Programming 24-Hour Trainer by Yakov Fain
1. Read chapter 17

2. Activity Time boxing

Table 1: Activity Time Boxing


Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20mins 20mins
6.2 Setting-up Path for JDK 5mins 5mins
6.3 Walkthrough Tasks 30mins 30mins
7 Practice tasks 20mins for each task 60mins
8 Evaluation Task 60mins for all assigned task 55mins

Department of Computer Science, Page 55


C.U.S.T.
Lab 6: Java Filing and Serialization

3. Objective of the experiment

 To be able to read and write data in a file.


 To learn how to preserve the state of object in database/file for later use.
 To learn to make another copy of the object without copying individual elements.
 To learn to save time of creating new object again and again, just de-serialize in few sec
and use it.
 To learn how to communicate between two machines using objects.

4. Concept Map

4.1. Implementing a simple file reader

1. Create a file named input.txt in the current working directory. Save and close the file after
adding the following line in that text file.

“This is Lab 4 of Advance Computer Programming”

2. Open Notepad and type the following code.

import java.io.*;

public class FileReaderDemo{

public static void main(String args[])throws IOException{

File in = new File("input.txt");


FileReader fr = new FileReader(in);
int c=0;
while((c=fr.read()) != -1)
System.out.print(c);
fr.close();
}
}

3. Save the file by the name of FileReaderDemo. Compile and execute the program. You will
see the following line on the screen after the successful execution of the program.

“This is Lab 4 of Advance Computer Programming”

4.1 Serialization

Object serialization is a mechanism in which object can be represented as a continuous sequence


of bytes that includes all the information stored in that particular object and the type of data it
holds. Once object is serialized it can be written in a file or sent on the network for other
computer to receive it. This is how information doesn't get lost and a class's object having many

Department of Computer Science, Page 56


C.U.S.T.
Lab 6: Java Filing and Serialization

attributes can be written using a single command.

4.2 Deserialization

Deserialization refers to the mechanism of reading that sequence of bytes back into the object,
after which we can use it for further processing. Whole procedure is JVM independent, which
means an object can be serialized on one platform and de-serialized on an entirely different
platform.

4.2.1 Streams to be used

Streams for serialization and deserialization are:

ObjectOutputStream:It is byte stream that serializes objects intobyte-encoded format, and


writesit on an output stream. It contains the following method

public final void writeObject(Object A) throws IOException{}

Return type is void means object A will be written and nothing will be returned back. It may
throw IOException.

ObjectInputStream: This input stream reads and reconstructsbytes into Objects. It contains
method readObject as:

public final Object readObject() throws IOException,ClassNotFoundException {}

Return type is Object which means object needs to be parsed to appropriate data type after
reading.

4.2.2 Serializable objects:

The class whose objects need to be serialized must fulfill certain conditions as:

1. The class must implement the java.io.Serializable interface


2. All of the fields in the class must be serializable. If a field is not serializable, it must be
marked transient or static. Refer to the following example to see how Serializable
interface is used in a class.

public class Student implements java.io.Serializable


{
public string name;
public string regNumber;
transientpublic intsemesterNo;
public void displayInfo()

Department of Computer Science, Page 57


C.U.S.T.
Lab 6: Java Filing and Serialization

{
System.out.println("Name"+ name+ " Reg number" + regNumber
+"semester Number"+semesterNo );
}
}

5. Homework before Lab

You must solve the following problems at home before the lab.

5.1 Problem Solution Modeling

After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you

5.1.1 Problem description:

What is serialization? Write an example of serialization?

6. Procedure& Tools

In this section, you will study how to work with serialization.

6.1 Tools

Java Development Kit (JDK) 1.7

6.2 Setting-up JDK 1.7 [Expected time = 5mins]

Refer to Lab 1 sec 6.2.

6.2.1 Compile and run a Program

Refer to lab 1 sec 6.2

6.3 Walkthrough Task [Expected time = 30mins]

This task is designed to guide you towards serializing and externalizing objects.

6.3.1 Implementing a simple file reader

Create a file named input.txt in the current working directory. Save and close the file after adding
the following line in that text file.

“This is Lab 4 of Advance Computer Programming”

Department of Computer Science, Page 58


C.U.S.T.
Lab 6: Java Filing and Serialization

Open Notepad and type the following code.

import java.io.*;

public class FileReaderDemo{

public static void main(String args[])throws IOException{

File in = new File("input.txt");


FileReader fr = new FileReader(in);
int c=0;
while((c=fr.read()) != -1)
System.out.print(c);
fr.close();
}
}

Save the file by the name of FileReaderDemo. Compile and execute the program. You will see
the following line on the screen after the successful execution of the program.

“This is Lab 4 of Advance Computer Programming”

6.3.2 Serialization

1. Create a class whose objects need to be serialized as the following class

public class Student implements java.io.Serializable


{
public string name;
public string regNumber;
transient public intsemesterNo;
public void displayInfo()
{
System.out.println("Name"+ name+ " Reg number" + regNumber
+"semester Number"+ semesterNo );
}
}

2. Create a driver class like the following to finally write the preserve the data of the above
class.

import java.io.*;
public class SerializableExample
{
public static void main (String [] args )
{

Department of Computer Science, Page 59


C.U.S.T.
Lab 6: Java Filing and Serialization

Student Student_1 =new Student ();


Student_1.name="Ali ";
Student_1. regNumber="bc103012";
Student_1.semesterNo=5;
try
{
FileOutputStream fos=new FileOutputStream ("first_file.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(Student_1); //writing object to the file named first_file
oos.close();//closing steams.
fos.close();
}
catch(Exception Ex1)
{
Ex1.printStackTrace();
}
}
}

3. Last step is to read the data back from the medium on which it was preserved. Following
class will show you how to deserialize the file.

import java.io.*;
public class SerializableExample
{
public static void main (String [] args )
{
Student Student_1 =new Student ();
try
{
FileInputStream fis=new FileInputStream ("first_file.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Student_1 =(Student) ois.readObject();
ois.close(); //closing steams.
fis.close();
}
catch (Exception Ex1)
{
Ex1.printStackTrace();
}
System.out.println("Deserialized student info ");
System.out.println("Name"+ Student_1 . name+ " Reg number" +
Student_1 .regNumber;
}
}

Department of Computer Science, Page 60


C.U.S.T.
Lab 6: Java Filing and Serialization

7. Practice Tasks

This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\dataserver\assignments$\Advanced Computer Programming\Lab5

7.1 Practice Task 1 [Expected time = 20mins]

Create a class (Java) “FlightRecords” consisting of following class attributes


I. Flight ID: IntII. Date: Date III. Departure timings: Date IV. Arrival timings: Date
V. Departure Route :StringVI. Arrival Route: String VII. No. of Passengers: int
VIII. No. of flight staff (pilot + air hostess) :Int

Using ArrayList of type” FlightRecords” add 5 flight records. Serialize and deserialize objects
sequentially.

7.2 Practice Task 2 [Expected time = 20mins]

Encryption is a technique to store data/information securely. You are required to make a class
Encryption. The class will contain following members: plaintext, key(int), encryptedText. Each
character of plain text will be encrypted by adding the key to ascii of the character. The key will
be shared by all the objects of the class and plaintext should not be saved to the file. Use
Serialization to save the object in the file.

Encryption formula for Uppercase : (((Ascii(char)-65)+key)%26)+65

Encryption formula Lowercase : (((Ascii(char)-97)+key)%26)+97

Hint: Convert all the letters to uppercase/lowercase of the plaintext to encrypt it correctly.
Sample Input/ Output:

Department of Computer Science, Page 61


C.U.S.T.
Lab 6: Java Filing and Serialization

7.3 Practice Task 3 [Expected time = 20mins]

Create StudentProfile class with UserName, EmailAddress, DomainOfInterest and Password.


You are required to store information of student profile but passwords needs to be secured. Write
a method of searching a particular student’s information. It can either be searched by email
address or user name.

7.4 Out comes

After completing this lab, student will be able to preserve the objects in-memory state using both
serialization.

7.5 Testing

Test Cases for Practice Task-1

Test cases will be provided by the instructor.

Test Cases for Practice Task-2

Test Cases for Practice Task-3

Test cases will be provided by the instructor.

8. Evaluation Task (Unseen) [Expected time = 60mins for two tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation criteria

The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).

Department of Computer Science, Page 62


C.U.S.T.
Lab 6: Java Filing and Serialization

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Reading

This section provides the references to further polish your skills.

10.1 Books

Text Book:
 Java: How to Program by Paul J. Deitel, Harvey M. Deitel. Eighth Edition
 Java Beginners Guide: http://www.oracle.com/events/global/en/java-outreach/resources/java-a-
beginners-guide-1720064.pdf
 http://exampledepot.8waytrips.com/ for the package by package examples

10.2 Slides

The slides and reading material can be accessed from the folder of the class instructor available
at \\dataserver\jinnah$\

Department of Computer Science, Page 63


C.U.S.T.

You might also like