Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 838
  • Last Modified:

How to serialize an object to create a file

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
gudii9
Asked:
gudii9
  • 10
  • 6
  • 6
2 Solutions
 
CEHJCommented:
How to serialize an object to create a file
You mean serialize an object to a file?
0
 
CPColinSenior Java ArchitectCommented:
CEHJ,

He's quoting this comment from a previous question.

gudii9,

That comment contains a link to a tutorial. Did it not work?
0
 
gudii9Author Commented:
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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
CPColinSenior Java ArchitectCommented:
Try putting a Windows path in there, with the backslashes escaped, something like: "c:\\temp\\employee.ser"
0
 
CEHJCommented:
Don't use a system root. Just use a simple file name such that it gets put in the current directory
0
 
gudii9Author Commented:
I will try and let you know soon
0
 
gudii9Author Commented:
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
 
gudii9Author Commented:
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
 
CEHJCommented:
So - you took no notice of my comment ;)
0
 
CPColinSenior Java ArchitectCommented:
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
 
gudii9Author Commented:
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
 
CPColinSenior Java ArchitectCommented:
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
 
gudii9Author Commented:
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
 
gudii9Author Commented:
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
 
gudii9Author Commented:
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
 
CEHJCommented:
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
 
CPColinSenior Java ArchitectCommented:
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
 
gudii9Author Commented:
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
 
CEHJCommented:
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
 
gudii9Author Commented:
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
 
CPColinSenior Java ArchitectCommented:
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
 
CEHJCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 10
  • 6
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now