Saving data structures in Java - 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.

Related

Java objects cannot be deserialized because of class structure change

I had serialized some objects of class into a file later the class structure had modified. So I cannot deserialize my object back. Please let me know how can I restore these objects?
To make it short: You should use your previous version of your java class and use it to read the serialized objects. Then you'll have to make a transition piece of software reading previous data and filling fields in the new object with this data before serializing this new version of your object.
You could:
Revert your class as it was before.
Create a new class which will have the new features.
Write an adapter class which places one class (the old) into another (the new).
Serialize the new version.

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............

Save LinkedList to file and Load List back to program

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.

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.

Permanent collections in Java

According to my assignment which asks to develop a small-scale Student Accommodation Management System :
The application should be developed using object-oriented concepts using Student class and Apartment class, implementing the appropriate data fields and methods for the classes. Data may be stored in collections i.e. array of objects, vectors, etc. or into data files except a database.
So far, I have worked with Sets. I am not sure if it the right way but I added HashSets to my classes. Example:
public static Set<Apartment> listOfApartments = new HashSet<Apartment>();
// in Apartment Class)
Now that I just realized I actually need persistent collections or some solutions to actually store the data permanently.
Any Suggestions?
If I where you I would use something such as an ArrayList to store data, especially students. Sets do not allow duplicate data so this could cause problems down the line.
With regards to persisting your data, you should take a look at the ObjectOutputStream to store your objects and to the ObjectInputStream to load them back into your application. You can take a look here for an ObjectStreams tutorial.
What I would recommend though is to use something such as XStream (you can see how to use it here). This will allow your application to store data in a human readable way (which is helpful for debugging) and will also allow your data to be read by different programming languages.
If Appartment is Serializable, then Set<Apartment> is also Serializable and doens't require any extra work to persist it using java.io classes
To make a class Serializable, you must :
make it implement the interface java.io.Serializable
add a default constructor
It is that easy

Categories