Save LinkedList to file and Load List back to program - java

I have a stock control system being used and i have a LinkedList to hold stock objects, now i need to add a method to the program that will allow me to save the linked list to a file and load the list from the file.
public void loadStockData(String filename)
and
public void saveStockData()
How would I achieve this?

Make sure your objects support serialization, hint: implements Serializable. http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html
Then, use java.io.ObjectOutputStream to save and java.io.ObjectInputStream to read the list.
http://www.tutorialspoint.com/java/java_serialization.htm

You did not mention if the file should be human readable.
If not then serialize the LinkedList object itself to the file given that the object it contains is also Serializable. You can use ObjectOutputStream to do that. Provide a FileOutputStream to the ObjectOutputStream
If you need in some specific format then you need to write the logic and using FileOutputStream you can write the file.

Related

Saving data structures in Java

Please give me some advice regarding data saving in Java.
I’m new in Java. Previously I wrote programs on C++.
It was easy to save data in C++: just declare structure, fill its fields and then save it like byte array. As far as Java doesn’t have structures I suppose that Java programming means another save concept.
I will appreciate you for ideas and ideas what to read regarding this.
It's simpler in Java.
Use a class in place of your C++ struct, and implement java.io.Serializable. Your IDE will help you build any methods that you need to implement. Conceptually Java uses reflection to capture the values of the fields (aside from ones you've marked Transient) in your class, so, by and large, the process is automated.
I am guessing, by 'saving' you mean saving to a disc.
If that is the case, you should be looking at the concept of serialization in Java.
Make your class implement the Serializable interface.
Then take cue from the following code to serialize.
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
Code on similar lines to deserialize.
In java instead of structure create a class corresponding to your storage criteria then create object for that class and then you can store the required datas in that object then store that object in array or any collections.
for eg create Student class which has name,regno etc.. then create object of student class store the datas in that object,so you can have your data in an object which is similar to structure then you can save students object in array or collections.

Is it recommended to serialize & deserialize objects that are stored in arrayList?

In my small bank application, users have to input some value (name, SSN, amount etc..) and they get stored in an arrayList. The arrayList size is dynamic.
But problem with this one is I loose all data once I terminate the application. That leads me to think about the implementation of writing and reading file (file I/O).
Now I also have come to know about something called serialization and deserialization, though I am not quite sure in what situation this need to be implemented.
Do I need it in my particular case or simply writing into and reading from file will be enough?
What serialization and deserialization has to do with file I/O?
[NOTE: I will give more info if necessary]
This is where a Database comes into picture. To start with, you can use MySQL DB - it' an excellent FREE Database for small to medium size business apps. Later, if you intend to deploy your app to production - with large number of users & advance features, and are ready to pay a price for it - you might consider other databases like Oracle etc.
Storing info to files ((De)Serialization) is not recommended for any practical application.
Serialization is a mechanism 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.
ArrayList already implements Serializable, so in your example you could write something like this:
ArrayList<String> al=new ArrayList<String>();
al.add("Jean");
al.add("Pierre");
al.add("John");
try{
FileOutputStream fos= new FileOutputStream("myfile.txt");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(al);
oos.close();
fos.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
Here we save the list al in the file myfile.txt.
To read the file and get your ArrayList back, you would use ObjectInputStream:
FileInputStream fis = new FileInputStream("myfile.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<String> list = (ArrayList<String>) ois.readObject();
ois.close();
Serialization is required when you want to write instances of your own class to a file. In your case, you can create a java class to hold all the values about customer, then override hashCode() and equals(), and then write your object to file. http://www.tutorialspoint.com/java/java_serialization.htm
Also, if you want, you can store individual field in file as well as int or String.
Though I would suggest to use a database to store all this information. But it seems you are a student and still in learning phase. So, interacting with DB right away might not be a good approach as of now.
Yes, you can use arraylist for serialization and deserialization.
Whenever u want to write and read the object into file and from file
respectively then u need to be object should be serialized and object
write into the file in byte stream format.that means ur data will be secure in
stream.you can used serialization interface:-
To persist data for future use.
To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
To "flatten" an object into array of bytes in memory.
To exchange data between applets and servlets.
To store user session in Web applications.
To activate/passivate enterprise java beans.
To send objects between the servers in a cluster.
and more............

Transfer of a Java Serialized Object

Is it possible to declare an instance of a serializable object in one Java program / class, then repeat the definitions of the internal objects in a different program /class entirely, and load in a big complex object from a data file? The goal is to be able to write an editor for items that's kept locally on my build machine, then write the game itself and distribute it to people who would like to play the game.
I'm writing a game in Java as a hobbyist project. Within my game, there's an a family of classes that extend a parent class, GameItem. Items might be in various families like HealingPotion, Bomb, KeyItem, and so on.
class GameItem implements Serializable {
String ItemName
String ImageResourceLocation
....}
What I want to do is include definitions of how to create each item in a particularly family of items, but then have a big class called GameItemList, which contains all possible items that can occur as you play the game.
class GameItemList implements Serializable {
LinkedList<GameItem>gameItemList;
//methods here like LookUpByName, LookUpByIndex that return references to an item
}
Maybe at some point - as the player starts a new game, or as the game launches, do something like:
//create itemList
FileInputStream fileIn = new FileInputStream("items.dat");
ObjectInputStream in = new ObjectInputStream(fileIn);
GameItemList allItems = (GameItemList)in.readObject();
in.close();
//Now I have an object called allItems that can be used for lookups.
Thanks guys, any comments or help would be greatly appreciated.
When you serialize an object, every field of the object is serialized, unless marked with transient. And this behavior is of course recursive. So yes, you can serialize an object, then deserialize it, and the deserialized object will have the same state as the serialized one. A different behavior would make serialization useless.
I wouldn't use native serialization for long-term storage of data, though. Serialized objects are hard to inspect, impossible to modify using a text editor, and maintaining backward compatibility with older versions of the classes is hard. I would use a more open format like XML or JSON.
Yes, that is possible. If an object is correctly serialized, it can be deserialized in any other machine as long as the application running there knowns the definition of the class to be deserialized.
This will work, but Java serialization is notorious for making it hard to "evolve" classes -- the internal representation is explicitly tied to the on-disk format. You can work around this with custom reader / writer methods, but you might consider a more portable format like JSON or XML instead of object serialization.

Why should i use Serialization instead of File I/O in java

In serialization mechanism,we are wrote the object into stream using objectinputstream and object outputstream.These objects passing across the network.In this mechanismusing a Object input/output stream.So Can i use File INPUT/OUTPUT Streams instead of calling serialization marker interface?.
I guess You are mixing up serialization and general I/O.
Serialization is a way to transform objects into byte sequences (and back, which is called Deserialization). This way, You can transmit serializable objects over the network and store them into files.
File input/output streams are for storing/reading any kind of data to/from files.
when you need to transfer your object on network, you need to serialized it. Below link might be useful for you.
http://java.sun.com/developer/technicalArticles/Programming/serialization/
File I/O and Serialization are two different things. File I/O is used to read/write a file. Serialization interface is used for binary interpretation of an object. So NO, you can't use File Streams for sending over network.(maybe there is some workaround for sending data over network using file streams, but its like trying to fly with a car)
First let's concentrate on the definition:
Serialization: It is the process of converting object state into a format that can be stored and reconstructed later in the same way.
Whereas in file I/O it can't be possible to store data-structure or object and reconstructed later in the same way.
That's why we use serialization or database query methods (like sql, mongodb).
JSON/XML can also be used for serialization using its parser.
Take an example of javascript (not java, but take it like language-agnostics):
var obj = { // it's an object in javascript (same like json)
a: "something",
b: 3,
c: "another"
};
Now if you try to use file i/o in this to save in a file (say abc.txt), it will be saved as a string
which means it can't be accessed later in other code by reading this file (abc.txt) like this:
// readThisFile();
// obj.a;
But if you use serialization (in javascript using JSON natively), you can read it from the file
Since streams are additive, you can do something like
FileOutputStream fos = new FileOutputStream("/some/file/to/write/to");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(someObject);
Not sure this is what you were asking, but it's hard to tell.
Serialization/Deserialization is used to read and write objects, which not only makes compressed data, which is unreadable but also is writes it in binary. The File I/O is used for reading and writing. It appears that you do not want to serialize, if you don't, well do not use it. Read and write your files in text.
In serialization mechanism,we write the object into s stream using
ObjectInputStream and ObjectOutputStream.
Ok
These objects are passed across the network.In this mechanism using a
ObjectInput/Output stream.
I am following you.
So can I use File Input/Output streams instead of calling
serialization marker interface?.
Here you lost me. Do you mean to send an object over the network or just to serialize it?
Of course you can use whichever Input/Output streams along with ObjectInput/ObjectOutput streams to serialize objects to different media.
For instance:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("jedis.bin"));
out.writeObject(new Jedi("Luke"));
Would serialize the object into a file called jedis.bin
And the code
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOputStream out = new ObjectOutputStream(byteStream);
out.writeObject(new Jedi("Luke"));
Would serialize the object into a memory array.
So, anything that is an output/input stream is subject of being used as the underlying stream used by ObjectInput/ObjectOutput streams.

Customizing Java Serialization

I was going through a blog and one question came to my head. Is it possible to overwrite the way ObjectOutputStream is writing.
Let's say i am writing to a file out.dat i.e.
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("C:\\out.dat")));
out.writeObject(o);
When i opened the file out.dat in Notepad++, i saw the binary data. Which makes sense. What if, I would like to customize the way this data is being written. Lets say i want my out.dat file in JSON format (Thats just an example, It could be any other format). What method should i overwrite to do this?
You'll be able to do what you want by implementing Externalizable and overriding the writeExternal and readExternal methods. See http://download.oracle.com/javase/7/docs/platform/serialization/spec/output.html#3146 for details.
Note that it will allow customizing the output of the serialization of one object, but not the format of the whole stream. You will thus find your JSON string inside other binary data.
i think that you shouldn do it, because this format is used to keep comunication between tiers (work with distributed objects on a network). What you can do is just create a handler that store your object in a file using your pretty format.
You can make your object implement Externalizable and have full control over serialization. Use e.g. google-gson for JSON when implementing the readExternal / writeExternal methods.
In your scenario , where you are looking for a custom serialization mechanism , I would recommend that you implement Externalizable interface and provide implementations of methods
public void writeExternal(ObjectOutput out) throws IOException
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
Its entirely up to you how you want to serialize in this case.
I'm pretty sure that java does not have internal support for serializing to JSON. In my opinion your best bet is to create a interface for a getting the JSON and have any objects you want serialized to JSON implement this interface:
public interface IJSONSerializable{
public String getSerializedForm();
}
And then use a basic FileOutputStream to output since (as I understand it) the ObjectOutputStream is used to serialize a object to binary and does not have inherent support for JSON.
Other Thoughts
If you choose to go this way you could write a helper class for writing out things such as a property and a value.
Well Java itself has no built-in support for JSON serialization, but then I'm sure you can find frameworks that do that - or just write it yourself for simple classes.
So for any class you want to serialize in JSON format just overwrite
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
Shouldn't be too hard if there's some JSON framework out there that gives you the data of one instance in string format and vice versa.

Categories