Solved

How to serialize an object to create a file

Posted on 2014-02-18
22
679 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
  • 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
 
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn how to implement Singleton Design Pattern in Java.

760 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now