Serialization of an arraylist which contains another arraylist - java

my research on google-search and stackoverflow regarding this problem didn't resolve it.
i'd like to show you a snipped of my Datastructure:
there's a class, called "SequenceHolder" => this one carries an:
ArrayList<SequenceData> data;
within the Sequenceholder, there is a function to call the serialization:
public void writeSequenceList() throws FileNotFoundException, IOException {
FileOutputStream fout = new FileOutputStream(path);
ObjectOutputStream oout = new ObjectOutputStream(fout);
oout.writeObject(data);
oout.close();
fout.close();
}
The class SequenceObject has following fields: (this one is on the top, where i start the serialization)
private ArrayList<SequenceModel> recordedSequenceData;
private String sequenceUrl;
while the SequenceModel is defined like this:
private Object sequenceRawData;
private boolean isProcessedByRequest;
The sequenceRawdata objects are basically two other classes (containing Strings only)!
every class of this "trail" implements the interface "Serializable".
this is the deserialization:
public ArrayList<SequenceData> loadSequenceList() throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream(path);
ObjectInputStream in = new ObjectInputStream(fileIn);
this.data = (ArrayList<SequenceData>) in.readObject();
in.close();
fileIn.close();
return data; // load from de-serialization
}
after a deserialization of the SequenceObject, i'll only retrieve the "sequenceUrl", but no recordedSequenceData.
Is there a trick to do this?!
It came just up to my mind, to extend some classes with the ObjectOutputStream and call the writingprocess with "this" explicitly in every class - but yeah, i am not sure if thats a good idead.

What do you mean by "The sequenceRawdata objects are basically two other classes (containing Strings only)!" because when I try to run the same program :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
class SequenceModel implements Serializable
{
public SequenceModel(Object a, boolean b)
{
sequenceRawData = a;
isProcessedByRequest = b;
}
public String toString()
{
return (String)sequenceRawData + isProcessedByRequest + " SeqModel ";
}
private Object sequenceRawData;
private boolean isProcessedByRequest;
}
class SequenceData implements Serializable
{
public SequenceData(ArrayList<SequenceModel> a, String b)
{
recordedSequenceData = a;
sequenceUrl = b;
}
public String toString()
{
return recordedSequenceData + sequenceUrl + " SeqData ";
}
private ArrayList<SequenceModel> recordedSequenceData;
private String sequenceUrl;
}
class SequenceHolder implements Serializable
{
ArrayList<SequenceData> data;
public String toString()
{
return data + " SeqHol ";
}
public SequenceHolder(ArrayList<SequenceData> a)
{
data = a;
}
public void writeSequenceList() throws FileNotFoundException, IOException {
FileOutputStream fout = new FileOutputStream(Test.file);
ObjectOutputStream oout = new ObjectOutputStream(fout);
oout.writeObject(data);
oout.close();
fout.close();
}
public ArrayList<SequenceData> loadSequenceList() throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream(Test.file);
ObjectInputStream in = new ObjectInputStream(fileIn);
this.data = (ArrayList<SequenceData>) in.readObject();
in.close();
fileIn.close();
return data; // load from de-serialization
}
}
public class Test
{
public static File file = new File("abc.txt");
public static void main(String[] args)
{
SequenceModel obj = new SequenceModel("abc", false);
ArrayList list = new ArrayList(); list.add(obj);
SequenceData obh = new SequenceData(list, "str");
ArrayList l2 = new ArrayList();
l2.add(obh);
SequenceHolder obi = new SequenceHolder(l2);
try {
obi.writeSequenceList();
System.out.println(obi.loadSequenceList());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
it is able to serialize and deserialize both and there is no problem.
Output it is printing is : [[abcfalse SeqModel ]str SeqData ] which includes everything as desired.
Please let me know if I am missing anything.

Related

How to deserialize objects after closing an opening program in Java 11

I have a program in which I am trying to implement saving and loading of obejcts, however I couldn't get the loading to work after the program closes, so effectively only saving and loading works while the program is open, but no data is ever loaded once the program starts. I assume this is something to do with overwiting. I created a test program to see if I could get it to work just using a simple Person class. I store my Peson objects inside an ArrayList and serialize it, then deserialize it. Currently I am storing all loaded Person objects in a JComboBox. I have looked online and could not find anything that will help. Also note I am aware that using serialization is not the best method of saving objects, but it's something suitable to use for my program.
My App Class:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
public class App extends JFrame {
public static JComboBox<Person> peopleBox;
public App(){
try {
Person.peopleList = loadList();
}
catch(IOException | ClassNotFoundException e){
System.out.println(e.getMessage());
}
try {
saveList(Person.peopleList);
}catch (IOException e){
System.out.println(e.getMessage());
}
peopleBox = new JComboBox<>();
peopleBox.setModel(getComboBoxModel(Person.peopleList));
add(peopleBox);
pack();
setSize(600, 400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public DefaultComboBoxModel<Person> getComboBoxModel(ArrayList<Person> peopleList){
Person[] comboBoxModel = peopleList.toArray(new Person[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
public static void saveList(ArrayList<Person> peopleList) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.bin"));
objectOutputStream.writeObject(peopleList);
}
public static ArrayList<Person> loadList() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test.bin"));
Person.peopleList = (ArrayList<Person>) objectInputStream.readObject();
return Person.peopleList;
}
public static void main(String[] args){
// Person p = new Person("Sean", 22);
try {
saveList(Person.peopleList);
}catch (IOException e){
System.out.println(e.getMessage());
}
App app = new App();
app.pack();
app.setVisible(true);
}
}
Person Class
import java.io.Serializable;
import java.util.ArrayList;
public class Person implements Serializable {
public int age;
public String name;
public static ArrayList<Person> peopleList = new ArrayList<>();
public Person(String name, int age){
this.age = age;
this.name = name;
peopleList.add(this);
for(Person p : peopleList){
System.out.println(p.toString());
}
}
public Person(){
}
public String toString(){
return "Name : " + name + " Age: " + age;
}
}
I expect when I save the list to the "test.bin" file, close the program, then open it again that it will load the list and display the Objects I created before I closed the program. I appreciate any help, thanks.
You are saving an empty list before you load Person from the file.
I suggest this approach:
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class App extends JFrame {
public static JComboBox<Person> peopleBox;
public App() {
try {
loadList();
} catch (IOException | ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
saveList(Person.peopleList);
} catch (IOException e) {
System.out.println(e.getMessage());
}
setSize(600, 400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void updateData(){
peopleBox = new JComboBox<>();
peopleBox.setModel(getComboBoxModel(Person.peopleList));
add(peopleBox);
pack();
}
public DefaultComboBoxModel<Person> getComboBoxModel(ArrayList<Person> peopleList) {
Person[] comboBoxModel = peopleList.toArray(new Person[0]);
return new DefaultComboBoxModel<>(comboBoxModel);
}
public static void saveList(ArrayList<Person> peopleList) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.bin"));
objectOutputStream.writeObject(peopleList);
}
public static void loadList() throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test.bin"));
Person.peopleList.addAll((List<Person>) objectInputStream.readObject());
}
public static void main(String[] args) {
App app = new App();
Person p = new Person("Sean2", 24);
try {
saveList(Person.peopleList);
} catch (IOException e) {
System.out.println(e.getMessage());
}
app.updateData();
app.setVisible(true);
}
}

Serialization issue : de.ruedigermoeller

Trying to get https://github.com/RuedigerMoeller/fast-serialization framework as drop in replacement for my JVM serializer. As a first step.
Here is my serializer:
static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration();
public Serialiser() {
conf.registerClass(MapSerializableForm.class, // etc// ...
}
public byte[] serialise(Object obj) {
byte[] bytes = null;
try {
final ByteArrayOutputStream b = new ByteArrayOutputStream();
final FSTObjectOutput o = new FSTObjectOutput(b);
o.writeObject(obj);
bytes = b.toByteArray();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
public Object deserialize(byte[] bytes) {
Object deser = null;
try {
final ByteArrayInputStream b = new ByteArrayInputStream(bytes);
final FSTObjectInput o = new FSTObjectInput(b);
deser = o.readObject();
b.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return deser;
}
The class that is causing me problems is this one: I'm wrapping JavaFX images with Swing images to help me serialise them. My code does work with the standard Java serializer, but is v. slow. I'm hopeful for improvements, if I can get it working. The result is a nullpointerException during deserialization. It's late, here, but I've tried to be clear.
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class SerializableImage implements Serializable {
private static final long serialVersionUID = 7984341875952256208L;
public transient Image image ;
public SerializableImage(Image image) {
this.image=image;
}
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
BufferedImage bufferedImage = ImageIO.read(s); //image comes back null !
image = SwingFXUtils.toFXImage(bufferedImage, null);
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", s);
}
public double getWidth() {
return image.getWidth();
}
In the readObject method, (inside the stream "s") I'm able to see an incoming FSTObjectInput with a wrappedStack of one object: this as hoped contains a SerializableImage in the "toRead" field. However, I'm uncertain how to get this out and into my BufferedImage:
BufferedImage bufferedImage = ImageIO.read(s);
Hence, currently, the image comes back null. I tried adding an FSTInput, but couldn't get it to work. Thanks for any help.

Reading objects from text file

I have a text file with serialized objects written it. The file contains data like this -
line[com.high.3449%]
line[com.high.58850?]
line[com.high.47646%]
I want to read this and store 1 by 1 in an arraylist. But when I read it I am just able to read the first line which is line[com.high.3449%] but not everything. I am using below logic to read -
List<MyData> myobjects1 = new ArrayList<MyData>();
List<MyData> myobjects2 = new ArrayList<MyData>();
FileInputStream fin = new FileInputStream("/storage/200B-431F/Documents/MyData.txt");
ois = new ObjectInputStream(fin);
try {
myobjects1 = (List<MyData>) ois.readObject();
while (myobjects1 != null) {
myobjects2.addAll(myobjects1);
Log.d("hi", "second arraylist " + myobjects2);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois.close();
server.sendData(myobjects2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) {}
Can someone help me how to read all the data and store in the arraylist myobjects2?
The issue seems to be related to your loop when you read back the data. There is no need to loop (it will loop forever)
Instead of
myobjects1 = (List<MyData>) ois.readObject();
while (myobjects1 != null) {
myobjects2.addAll(myobjects1);
...
You should use
myobjects1 = (List<MyData>) ois.readObject();
if (myobjects1 != null) {
myobjects2.addAll(myobjects1);
}
If you want to loop through the myobjects you need to use something like
for (MyData myData : myobjects1) {
myobjects2.add(myData);
}
Am adding the code I used to test the answer.
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class LoadFileObject {
public static class MyData implements Serializable {
private String line, content;
public MyData(String line, String content) {
setLine(line);
setContent(content);
}
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content= content;
}
public String toString() {
return (line+content);
}
}
#Test
public void doWork() throws Exception {
List<MyData> myobjects1 = new ArrayList<MyData>();
myobjects1.add(new MyData("l1", "content1"));
myobjects1.add(new MyData("l2", "content2"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("mydata.txt"));
oos.writeObject(myobjects1);
oos.close();
List<MyData> myobjects2 = new ArrayList<MyData>();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("mydata.txt"));
myobjects2 = (List<MyData>) ois.readObject();
System.out.println("read:" + myobjects2.size());
for (MyData myData : myobjects2) {
System.out.println("myData line:" + myData.getLine() + " content:" + myData.getContent());
}
}
}
try this :
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("/storage/200B-431F/Documents/MyData.txt/CPU.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
// here line variable will hold the data for each line of your text file
// i.e you can add the string to the arrayList here
myObjects2.add(line);
}
} catch (FileNotFoundException ex) {
}
catch (IOException ex) {
}

What are the errors of this Java code?

package example;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Object;
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
public class mytest {
public static void main(String[] args) throws IOException {
clone
}
}
For above code, it wants to show the deep copy of Java. But myeclipse reports some errors. But I don't know what is wrong with it?
Could anyone please help to point them out?
Changed the code according to your suggestion.
package example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.Object;
class Utils {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}
public class mytest {
public static void main(String[] args) throws IOException {
Object clonedObject = Utils.copy(new Object());
clonedObject.notifyAll();
}
}
Further:
Thank you all!
I modifeid the code like above, it becomes better but still cannot run normally.
The new error message is below:
Any new suggestion?
You can't have floating methods in Java. Everything must be a member of a class. In this instance, a dummy class with only static methods called Utils would be common practice.
e.g.
public class Utils {
// Static methods go here
public static Object copy(Object oldObj) {
// etc
}
}
Then you can call it like so:
public class mytest {
public static void main(String[] args) throws IOException {
Object clonedObject = Utils.copy(new Object());
// etc
}
}
Here are the following steps to solve your errors:
Make a package inside a Project(Specific Name)
Inside a created package make a name MyTest.
Write or copy the method into that class which has been created
above.
To Run the Program Make one main Method any call it by there name if
it is static.
If your method is not static make a object of the class and call by
that object of the class.
It will solve your Error & also run your program...
Note: Try to put finally block to free the resources like object, ByteArrayOutputStream & ObjectStream etc.... It will increase your performance of the program.
You need to put a method into a class.
public class SomeClass{
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
And you can use it as:
public class mytest {
public static void main(String[] args) throws IOException {
Object object = Someclass.copy(someObject);
}
}
You can't declare methods (even static ones) outside of a class in Java. You would have to put everything (except the imports) inside a class.
You'll need something like:
public class YourClass {
public static Object copy(Object oldObj) {
...
}
}
The method public static Object copy(Object oldObj) isn't located in a class. That's why you are getting the error.
You must add a class named mytest as the 'top level scope' of this file, nest all other methods in it.
class mytest {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
public class mytest {
public static void main(String[] args) throws IOException {
clone
}
}
}
As a side note, you should rename the class name (and file name) to MyTest and MyTest.java - to match the java coding convention.
You should put your method in a class, preferably called mytest since it's the name of the file, declared like
public class mytest {
//Your method here
}
Also note that the naming convention in Java is to have class names starting with a capital letter, so it would be MyTest, and your file should be renamed to reflect that.
Try
public class MyTest {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
public static void main(String[] args) throws IOException {
clone
}
}
There are no methods who do not belong to a class (like a JavaScript-Function).
Static means that the method does belong to the class and not to an instance of the class as a non static method would do
You can't write methods outside the class. Put your method #copy inside the class. like this:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class mytest
{
public static void main(String[] args) throws IOException
{
// Now you can use your method here
}
public static Object copy(Object oldObj)
{
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}
Where is the class here? these method should contain a class.
Your java class should looks like this
package name;
imports;
public class MyClass{
public void myMethod(){
}
}

serializing a list of objects into a file in java

I have a list of around 20,000 object, which in turn have a very huge hierarchy. I need to dump the objects into a file, so that i can read it later anytime during my process. Now my problem is, I have worked on Java but not that much on serialization and i dont have that much of knowledge how to do that.
In this case as far as i know, i need to use both Serialization ane De-Serialization. Can anyone please help. Also i can use any new API or normal Java Serialization.
Regards.
Look at this link http://www.java2s.com/Code/Java/File-Input-Output/Objectserialization.htm
Its something like this:
Card3 card = new Card3(12, Card3.SPADES);
System.out.println("Card to write is: " + card);
try {
FileOutputStream out = new FileOutputStream("card.out");
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(card);
oos.flush();
} catch (Exception e) {
System.out.println("Problem serializing: " + e);
}
Card3 acard = null;
try {
FileInputStream in = new FileInputStream("card.out");
ObjectInputStream ois = new ObjectInputStream(in);
acard = (Card3) (ois.readObject());
} catch (Exception e) {
System.out.println("Problem serializing: " + e);
}
System.out.println("Card read is: " + acard);
Don't forget to implement Serializable interface in all class you want to save
and put modifier "transient" at all fields you don't want to save.
(e.g. private transient List cache;)
Rather than saving every object individually you can directly save the list of objects. I am using below code to achieve this. Although I am serializing for cloning, it should be sufficient to learn the basics.
public static List<EmpoyeeTO> deepCloneList( List<EmpoyeeTO> objectList) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(objectList);
oos.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (List<EmpoyeeTO>) ois.readObject();
}catch(EOFException eof){
return objectList;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
JSON is all the rage recently so you can use that. Jackson is a nice api for JSON serialization/deserialization. As a bonus you get interoperability with other platforms.
If you're not affraid of xml use JAXB
Of course you can always use binary serialization, but IMO text is easier to manage than blobs.
below is the code to write objects to file using XMLEncoder, assuming that your object implements Serializable Interface.
FileOutputStream os =new FileOutputStream("c:/temp/serialized.xml");
XMLEncoder encoder=new XMLEncoder(os);
encoder.writeObject(objectToBeSerialized);
encoder.close();
Below is the code to deserializ the Data
FileInputStream is=new FileInputStream("c:/temp/serialized.xml");
XMLDecoder decoder=new XMLDecoder(is);
Object object=(Object)decoder.readObject();
decoder.close();
I give you a sample
import java.io.Serializable;
public class Account implements Serializable {
private int accountNo;
private String custName;
private int balance;
/** Creates a new instance of Account */
public Account(int accNo, String name, int bal) {
this.accountNo = accNo;
this.custName = name;
this.balance = bal;
}
#Override
public String toString() {
String str = "Account No:" + this.accountNo;
str += "\nCustomer name:" + this.custName;
str += "\nBalance:" + this.balance;
return str;
}
}
Write and read object
package me.dev;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public void writeObject(ArrayList<Object> listAccount) throws IOException {
//Create FileOutputStream to write file
FileOutputStream fos = new FileOutputStream("C:\\bank.datum");
//Create ObjectOutputStream to write object
ObjectOutputStream objOutputStream = new ObjectOutputStream(fos);
//Write object to file
for (Object obj : listAccount) {
objOutputStream.writeObject(obj);
objOutputStream.reset();
}
objOutputStream.close();
}
public ArrayList<Account> readObject() throws ClassNotFoundException, IOException {
ArrayList<Account> listAccount = new ArrayList();
//Create new FileInputStream object to read file
FileInputStream fis = new FileInputStream("C:\\bank.datum");
//Create new ObjectInputStream object to read object from file
ObjectInputStream obj = new ObjectInputStream(fis);
try {
while (fis.available() != -1) {
//Read object from file
Account acc = (Account) obj.readObject();
listAccount.add(acc);
}
} catch (EOFException ex) {
//ex.printStackTrace();
}
return listAccount;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws ClassNotFoundException {
try {
// TODO code application logic here
ArrayList<Object> listAcc = new ArrayList<Object>();
listAcc.add(new Account(1, "John", 1000));
listAcc.add(new Account(2, "Smith", 2000));
listAcc.add(new Account(3, "Tom", 3000));
Main main = new Main();
main.writeObject(listAcc);
ArrayList<Account> listAccount = main.readObject();
System.out.println("listisze:" + listAccount.size());
if (listAccount.size() > 0) {
for (Account account : listAccount) {
System.out.println(((Account) account).toString());
}
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Categories

Resources