Solved

How to serialize an object to create a file

Posted on 2014-02-18
22
733 Views
Last Modified: 2014-03-27
How to serialize an object to create a file is really a new/different question. I am working on windows laptop using eclipse as IDE. I want a simple example that i can run and see on my laptop.

please advise
Any links resources ideas highly appreciated. Thanks in advance
0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 6
  • 6
22 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 39868682
How to serialize an object to create a file
You mean serialize an object to a file?
0
 
LVL 14

Expert Comment

by:CPColin
ID: 39868695
CEHJ,

He's quoting this comment from a previous question.

gudii9,

That comment contains a link to a tutorial. Did it not work?
0
 
LVL 7

Author Comment

by:gudii9
ID: 39871344
http://www.tutorialspoint.com/java/java_serialization.htm

the file created in the link example is on linux, with a path to the file as : /tmp/employee.ser"


I am looking for example which i can run on my windows 7 laptop environment but not linux. please advise
0
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
LVL 14

Expert Comment

by:CPColin
ID: 39871365
Try putting a Windows path in there, with the backslashes escaped, something like: "c:\\temp\\employee.ser"
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39871459
Don't use a system root. Just use a simple file name such that it gets put in the current directory
0
 
LVL 7

Author Comment

by:gudii9
ID: 39880959
I will try and let you know soon
0
 
LVL 7

Author Comment

by:gudii9
ID: 39880977
I have modified code as below

import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         //FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         //c:\\temp\\employee.ser
         FileInputStream fileIn = new FileInputStream("c:\\temp\\employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}

Open in new window


import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

Open in new window




public class Employee implements java.io.Serializable
{
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}

Open in new window

I got below error

java.io.FileNotFoundException: c:\temp\employee.ser (The system cannot find the path specified)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.<init>(Unknown Source)
      at java.io.FileInputStream.<init>(Unknown Source)
      at DeserializeDemo.main(DeserializeDemo.java:11)


How to fix the error
0
 
LVL 7

Author Comment

by:gudii9
ID: 39880978
import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         //FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         //c:\\temp\\employee.ser
         FileInputStream fileIn = new FileInputStream("employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}

Open in new window


I tried as above path that also did not work. Please advise
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39881031
So - you took no notice of my comment ;)
0
 
LVL 14

Assisted Solution

by:CPColin
CPColin earned 200 total points
ID: 39881041
In the version of the code where the path is "c:\\temp\\employee.ser" I bet the c:\temp directory does not exist. Java won't create directories that don't exist.

In the version of the code where you used the path "employee.ser" with no slashes at all, what happened? Did you have an error? Did you use Windows Search to search for employee.ser? Did you right-click on the project in Eclipse and select Refresh?
0
 
LVL 7

Author Comment

by:gudii9
ID: 39881500
In the version of the code where you used the path "employee.ser" with no slashes at all, what happened?
FileInputStream fileIn = new FileInputStream("employee.ser");

java.io.FileNotFoundException: employee.ser (The system cannot find the file specified)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.<init>(Unknown Source)
      at java.io.FileInputStream.<init>(Unknown Source)
      at DeserializeDemo.main(DeserializeDemo.java:11


when i gave like
         FileInputStream fileIn = new FileInputStream("c:\\employee.ser");

I got as below
java.io.FileNotFoundException: c:\employee.ser (The system cannot find the file specified)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.<init>(Unknown Source)
      at java.io.FileInputStream.<init>(Unknown Source)
      at DeserializeDemo.main(DeserializeDemo.java:11)



Don't use a system root. Just use a simple file name such that it gets put in the current directory

you mean like this right
FileInputStream fileIn = new FileInputStream("employee.ser");
that also did not work

java.io.FileNotFoundException: employee.ser (The system cannot find the file specified)
      at java.io.FileInputStream.open(Native Method)
      at java.io.FileInputStream.<init>(Unknown Source)
      at java.io.FileInputStream.<init>(Unknown Source)
      at DeserializeDemo.main(DeserializeDemo.java:11)


please advise
0
 
LVL 14

Expert Comment

by:CPColin
ID: 39881506
Oh, those are FileInputStreams. If the file doesn't exist, you can't make an input stream that points at it. You need to run your SerializeDemo class so it creates the file first.
0
 
LVL 7

Author Comment

by:gudii9
ID: 39881527
import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("c:\\temp\\employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

I tried running it
got similar error
java.io.FileNotFoundException: c:\temp\employee.ser (The system cannot find the path specified)
      at java.io.FileOutputStream.open(Native Method)
      at java.io.FileOutputStream.<init>(Unknown Source)
      at java.io.FileOutputStream.<init>(Unknown Source)
      at SerializeDemo.main(SerializeDemo.java:15)
0
 
LVL 7

Author Comment

by:gudii9
ID: 39881528
import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("c:\\employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

Open in new window


I also tried without temp still similar error
java.io.FileNotFoundException: c:\employee.ser (Access is denied)
      at java.io.FileOutputStream.open(Native Method)
      at java.io.FileOutputStream.<init>(Unknown Source)
      at java.io.FileOutputStream.<init>(Unknown Source)
      at SerializeDemo.main(SerializeDemo.java:15)
please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 39881531
I created test folder under C drive then it worked
import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;
      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("c:\\test\\employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /test/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

import java.io.*;
public class DeserializeDemo
{
   public static void main(String [] args)
   {
      Employee e = null;
      try
      {
         //FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         //c:\\employee.ser
         FileInputStream fileIn = new FileInputStream("c:\\test\\employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
    }
}

Open in new window

I got output
Deserialized Employee...
Name: Reyan Ali
Address: Phokka Kuan, Ambehta Peer
SSN: 0
Number: 101





Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

i do not see in outpyt object type and type of data( it is like int, double etc??)

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

How is it jvm independent?


please advise
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39882105
java.io.FileNotFoundException: c:\employee.ser (Access is denied)

Open in new window


You can't as an ordinary user create a file in C: - it's a privileged location. You shouldn't in any case be working off the root directly - it causes admin problems with stuff like backups. Use your home directory
0
 
LVL 14

Expert Comment

by:CPColin
ID: 39890719
i do not see in outpyt object type and type of data( it is like int, double etc??)

The object type data is embedded in the serialized form of the object. You can see it if you open the serialized file in a hex editor. You don't normally have to worry about it.

How is it jvm independent?

Because the format is so strictly specified, different platforms always serialize and deserialize objects the same way. This helps takes care of the major programming headache called endianness.
0
 
LVL 7

Author Comment

by:gudii9
ID: 39893919
Use your home directory

what is home directory. How to know?
How is it jvm independent?


Because the format is so strictly specified, different platforms always serialize and deserialize objects the same way. This helps takes care of the major programming headache called endianness.


can you elabiorate on this. Is JVM and platform are dependent, no right.

Then how the serialize objects happen same in different operating systems.
please advise
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39894424
what is home directory. How to know?

http://technojeeves.com/index.php/aliasjava1/16-javasystemproperties

java Props user.home

Open in new window


Then how the serialize objects happen same in different operating systems.
please advise
The serialization format is essentially a file format, so serialization can be done just as a PDF file can be read across different platforms
0
 
LVL 7

Author Comment

by:gudii9
ID: 39954109
he object type data is embedded in the serialized form of the object. You can see it if you open the serialized file in a hex editor. You don't normally have to worry about it.

How to install Hex editor to open and see the serialized file. please advise
0
 
LVL 14

Expert Comment

by:CPColin
ID: 39954123
Use your favorite search engine to find a hex editor and try it out. The use of a hex editor is really a separate question that's not very related to serialization. The point is that you don't have to worry about the exact format of serialized data, because the Java platform takes care of it for you.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 300 total points
ID: 39954151
Very quick and dirty hex dumper:

import net.proteanit.io.IOUtils;

public class DumpSer {
    public static void main(String[] args) {
	byte[] bytes = IOUtils.fileToByteArray(args[0]);
	System.out.println(new sun.misc.HexDumpEncoder().encodeBuffer(bytes));
    }
}

Open in new window


http://technojeeves.com/tech/IOUtils.java

Quicker still:

import java.io.*;

public class HexDumper {
    public static void main(String[] args) throws IOException {
        new sun.misc.HexDumpEncoder().encodeBuffer(new FileInputStream(args[0]), System.out);
    }
}

Open in new window

0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java string replace 11 77
How to convert from xls to xlsx using java 7 159
ejb entity bean example 2 57
Print Rhino Java Array in Javascript 1 58
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question