Posted on • Originally published atsaimhafeez.com
Read and Sort Data Generically - Generics in Java
I will demonstrate a Generic Java Class that willread and write the objects any type of object passed to it (anyPrimitive Datatype or your custom classes Like Explained in this example)
Consider, you have a Class NamedStudents in which there isname andid for a student.
Now Also Consider another class namedEmployees which also hasname,id andworkhours.
Now we want to implement a Generic class which willautomatically writes the object to a file with file name begin the name of the class. Now if there is already a.txt file of that same class then it shouldappend the file with given new object.
The Program should also be capable toread the required file. Theread() method willreturn the genericArrayList which we can typecast to our required object like if we want to read the Students list stored in txt file then the read() method will return a Generic ArrayList and we cantypecast it toStudents ArrayList and Easily Use it.
Hence Completes our Requirement,
A Program the read and write any type of objects plus it writes the same type objects in their own text files (Appends if already present or create new if object of such type is written for the 1st time) making it awesome code that handles the files automatically.
QUICK THINGS TO KNOW BEFORE STARTING
So First I have made two classes namedStudents.java andEmployees.java and my main class isMain.java.
Main.java is shown at the end of this post, while Student.java & Employees.java is not shown for the sake of complexity but if you do need to see them.
VisitHere for more detailed explanation with output explanation.
InStudents.java I have made aConstructor,getters andsetters forname andid
IN Both Classes I Have Made A Method NamedgetData() That Just DisplaysThe Data (Name, Id, workhours etc) of our Object.
Implementing Generic Class
Making A Generic Class
I have made a class nameGenericRead_Write.java and I haveparameterized it by using. We also created a field namedobject withType T. Now inConstructor I have set theinstance object with the locally passedobject. The Purpose ofstate variable is explained incode.
public class GenericRead_Write<T>{ T object; int state = 0; public GenericRead_Write(T object){ this.object = object; } public void write(){/* CODE EXPLAINED NEXT */}; public ArrayList<T> read(){/* CODE EXPLAINED NEXT */};}
Generic write() Method
public void write(){ state = 1; String fileName = object.getClass().getName() + ".txt"; ArrayList<T> list = new ArrayList<>(); list = read(); list.add(object); try { FileOutputStream file = new FileOutputStream(fileName); ObjectOutputStream outputFile = new ObjectOutputStream(file); for (T obj: list) { outputFile.writeObject(obj); } }catch (Exception e){ JOptionPane.showMessageDialog(null, e.getMessage()); } }
Explanation
String fileName = object.getClass().getName() + ".txt";
This basically gets the name of theobject you passed in Generic Class with appending.txt at the end of it. Next we will make a ArrayList with T as type parameter with name list.
list = read()
At Forth Line we calls theread() method to check if there is file with namefileName is already present or not. If it is present then we read that file and store objects in list Assuming that there is not file present for Students or Employees [These are two test classes I made for the sake of demonstration] at this point, we add the object passed by the user to the ArrayList named list. And in Try and Catch Block we are make a object ofFileOutStream with file name being thefilename (it also automatically creates the file with that name if it is not present) and then we make an object forObjectOutputStream to write the object to file. And finally, By Using Foreach Loop we are writing the object to file. Before compiling, There is no file.
After Comiling Programs creates a text file with our class name and package name being at start. See Below
Generic read() Method
public ArrayList<T> read() { String fileName = object.getClass().getName() + ".txt"; ArrayList<T> list = new ArrayList<>(); try{ FileInputStream file = new FileInputStream(fileName); ObjectInputStream inputFile = new ObjectInputStream(file); boolean END_OF_FILE = false; while (!END_OF_FILE){ try { list.add((T) inputFile.readObject()); }catch (EOFException e){ // When reaches END OF FILE we set the Boolean END_OF_FILE to TRUE END_OF_FILE = true; }catch (Exception e){ JOptionPane.showMessageDialog(null, e.getMessage()); } } }catch (FileNotFoundException j){ if(state == 1){ // Do Nothing... When state is 1 it means the write method is called // Since, the wite method will automatcally create new file is not found // So we don't require our program to show exception if read() is called from write() }else { // When state is 0 means the write() is not called so if file does not exits // in this case we show Error Message that file is not found JOptionPane.showMessageDialog(null, j.getMessage()); } }catch (Exception e){ JOptionPane.showMessageDialog(null, e.getMessage()); } return list; }
Explanation
First of All this method will return a generic ArrayList so we usedArrayList<T>
as return type.
Just like Previous we are creating a accuratefileName andArrayList namedlist. Now to read objects we will use object ofFileInputStream and pass it toobjectInputStream. Now we will make a boolean varibale namedEND_OF_FILE which initially will befalse now in while loop we cannot (!) theEND_OF_FILE So, loop will run and read the objects and store them toArrayList. Now incatch statement we can useEOFException (END OF FILE Exception) and when we reach the end we can simply put theEND_OF_FILE equals toTRUE Hence Loop will end. Now we can simply return thelist.
Now atMain.java we can access methods of our objects returned by this list by using typecasting.
That's it!, for now
If you have any question, ask me in the comment section.
Visit,my site for more Tutorials and examples
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse