How to deserialize multiple objects from file - java

How do I deserialize multiple objects from a file? Following is code that I have tried which works fine for one object but not for multiple objects.
public List<Show> populateDataFromFile(String fileName) {
// TODO Auto-generated method stub
Show s = null;
//FileInputStream fileIn=null;
try
{
FileInputStream fileIn=new FileInputStream("C:\\Users\\Admin\\Desktop\\Participant_Workspace\\Q1\\ShowBookingSystem\\ShowDetails.ser");
int i=0;
while((i=fileIn.read())!=-1){
// fileIn = new FileInputStream("C:\\Users\\Admin\\Desktop\\Participant_Workspace\\Q1\\ShowBookingSystem\\ShowDetails.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
s = (Show) in.readObject();
in.close();
fileIn.close();
System.out.println("Name: " + s.getShowName());
System.out.println("Show Time: " + s.getShowTime());
System.out.println("Seats Available: " + s.getSeatsAvailable());
}
}catch(IOException i)
{
i.printStackTrace();
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
}
return null;
}
I even tried using
while((i=fin.read())!=-1)
but it did not work. What change do I need to make?

Try this way:
Show s = null;
try {
FileInputStream fileIn = new FileInputStream(".....");
ObjectInputStream in = new ObjectInputStream(fileIn);
while (true) {
try {
s = (Show) in.readObject();
} catch (IOException ex) {
break;
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Name: " + s.getShowName());
System.out.println("Show Time: " + s.getShowTime());
System.out.println("Seats Available: " + s.getSeatsAvailable());
}
in.close();
fileIn.close();

Below is a short working example. You will need to remove the ObjectInputStream in = new ObjectInputStream(fileIn); from outside the while loop as well.
FileInputStream fis = new FileInputStream("...");
ObjectInputStream ois = new ObjectInputStream(fis); //<- Outside the while loop.
try
{
while(true)
{
Student std = (Student)ois.readObject();
System.out.println(std.getName());
System.out.println(std.getAge());
}
}
catch(IOException e)
{
e.printStackTrace(); //This exception will be thrown if the End Of File (EOF) is reached.
//
}
finally
{
fis.close(); //<- Outside the while loop.
ois.close(); //<- Outside the while loop.
}

In this case the solution is:
to put all objects in a list
serialize the list
This way you only have one object to de-serialize: the list. (As a bonus you get your object in a nicely organised (or not!) list).
If you have multiples type of object to serialize, serialize them in a list per class. Each list in a different file.

Related

Change ArrayList from an Object to more specific type

Is it possible to change the object type of an array list i.e. from an Object ArrayList to a specific object ArrayList. I have tried using a for each. Alternatively is there a way to change the filehandling method such that it can return a specific type depending on which file it reads from without duplicating code?
My Attempt:
ArrayList<Object> librarianList = FileHandling.getLibrarianRecords(fileName);
ArrayList<Librarian> libList = new ArrayList<>();
for (Object addType: librarianList) {
libList.add(addType);
}
getLibrarianRecords code
public static ArrayList<Object> getLibrarianRecords(String filename){
ArrayList<Object> fromFile = new ArrayList<>(); //Array of
// existing librarians
try{
FileInputStream fIS =
new FileInputStream(SYSTEM_PATH + filename);
ObjectInputStream oIS = new ObjectInputStream(fIS);
fromFile = (ArrayList<Object>)oIS.readObject();
} catch (IOException ex){
System.out.println("Failed to read from file " + ex.getMessage());
ex.printStackTrace(); //Catches an IO exception.
} catch (ClassNotFoundException ex){
System.out.println("Error class not found" + ex.getMessage());
ex.printStackTrace(); //Catches a class not found
// exception.
}
return fromFile; //Returns the array list.
}
It is rarely a good idea to read objects from a file like this. That said all you really need to do is to cast the result of oIS.readObject() to an ArrayList<Librarian> instead of carrying it to ArrayList<Object> (as you do now) and then amend the return type of getLibrarianRecords. Oh, and naturally also the type of the local variable fromFile.
public static ArrayList<Librarian> getLibrarianRecords(String filename){
ArrayList<Librarian> fromFile = new ArrayList<>(); //Array of
// existing librarians
try{
FileInputStream fIS =
new FileInputStream(SYSTEM_PATH + filename);
ObjectInputStream oIS = new ObjectInputStream(fIS);
fromFile = (ArrayList<Librarian>)oIS.readObject();
} catch (IOException ex){
System.out.println("Failed to read from file " + ex.getMessage());
ex.printStackTrace(); //Catches an IO exception.
} catch (ClassNotFoundException ex){
System.out.println("Error class not found" + ex.getMessage());
ex.printStackTrace(); //Catches a class not found
// exception.
}
return fromFile; //Returns the array list.
}
There should then be no need to loop over the list to actually do the type conversion on an element by element basis.
Thanks to #user3170251 for suggesting casting
ArrayList<Object> librarianList = FileHandling.getLibrarianRecords(fileName);
ArrayList<Librarian> libList = new ArrayList<>();
for (Object addType: librarianList) {
libList.add((Librarian) addType);
}
For changing the type this does work.
You can use this generic class definition
class ArrayListConverter<T> {
List<T> cast;
public ArrayListConverter(List<T> typeList){
cast = new ArrayList<>();
for (Object addType: typeList) {
cast.add((T)addType);
}
}
public List<T> getList(){
return cast;
}
}
Just do this:
ArrayListConverter<Librarian> conv = new ArrayListConverter<>(libList);
ArrayList<Librarian> libListOg = conv.getList();

Java too many open files exception

I have a problem on my code; basically I have an array containing some key:
String[] ComputerScience = { "A", "B", "C", "D" };
And so on, containing 40 entries.
My code reads 900 pdf from 40 folder corresponding to each element of ComputerScience, manipulates the extracted text and stores the output in a file named A.txt , B.txt, ecc ...
Each folder "A", "B", ecc contains 900 pdf.
After a lot of documents, an exception "Too many open files" is thrown.
I'm supposing that I am correctly closing files handler.
static boolean writeOccurencesFile(String WORDLIST,String categoria, TreeMap<String,Integer> map) {
File dizionario = new File(WORDLIST);
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
File cat_out = new File("files/" + categoria + ".txt");
fileWriter = new FileWriter(cat_out, true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fileReader = new FileReader(dizionario);
} catch (FileNotFoundException e) { }
try {
BufferedReader bufferedReader = new BufferedReader(fileReader);
if (dizionario.exists()) {
StringBuffer stringBuffer = new StringBuffer();
String parola;
StringBuffer line = new StringBuffer();
int contatore_index_parola = 1;
while ((parola = bufferedReader.readLine()) != null) {
if (map.containsKey(parola) && !parola.isEmpty()) {
line.append(contatore_index_parola + ":" + map.get(parola).intValue() + " ");
map.remove(parola);
}
contatore_index_parola++;
}
if (! line.toString().isEmpty()) {
fileWriter.append(getCategoryID(categoria) + " " + line + "\n"); // print riga completa documento N x1:y x2:a ...
}
} else { System.err.println("Dictionary file not found."); }
bufferedReader.close();
fileReader.close();
fileWriter.close();
} catch (IOException e) { return false;}
catch (NullPointerException ex ) { return false;}
finally {
try {
fileReader.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
But the error still comes. ( it is thrown at:)
try {
File cat_out = new File("files/" + categoria + ".txt");
fileWriter = new FileWriter(cat_out, true);
} catch (IOException e) {
e.printStackTrace();
}
Thank you.
EDIT: SOLVED
I found the solution, there was, in the main function in which writeOccurencesFile is called, another function that create a RandomAccessFile and doesn't close it.
The debugger sais that Exception has thrown in writeOccurencesFile but using Java Leak Detector i found out that the pdf were already opened and not close after parsing to pure text.
Thank you!
Try using this utility specifically designed for the purpose.
This Java agent is a utility that keeps track of where/when/who opened files in your JVM. You can have the agent trace these operations to find out about the access pattern or handle leaks, and dump the list of currently open files and where/when/who opened them.
When the exception occurs, this agent will dump the list, allowing you to find out where a large number of file descriptors are in use.
i have tried using try-with resources; but the problem remains.
Also running in system macos built-in console print out a FileNotFound exception at the line of FileWriter fileWriter = ...
static boolean writeOccurencesFile(String WORDLIST,String categoria, TreeMap<String,Integer> map) {
File dizionario = new File(WORDLIST);
try (FileWriter fileWriter = new FileWriter( "files/" + categoria + ".txt" , true)) {
try (FileReader fileReader = new FileReader(dizionario)) {
try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
if (dizionario.exists()) {
StringBuffer stringBuffer = new StringBuffer();
String parola;
StringBuffer line = new StringBuffer();
int contatore_index_parola = 1;
while ((parola = bufferedReader.readLine()) != null) {
if (map.containsKey(parola) && !parola.isEmpty()) {
line.append(contatore_index_parola + ":" + map.get(parola).intValue() + " ");
map.remove(parola);
}
contatore_index_parola++;
}
if (!line.toString().isEmpty()) {
fileWriter.append(getCategoryID(categoria) + " " + line + "\n"); // print riga completa documento N x1:y x2:a ...
}
} else {
System.err.println("Dictionary file not found.");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
This is the code that i am using now, although the bad managing of Exception, why the files seem to be not closed?
Now i am making a test with File Leak Detector
Maybe your code raises another exception that you are not handling. Try add catch (Exception e) before finally block
You also can move BufferedReader declaration out the try and close it in finally

Loading object from .dat file

I'm having an issue loading objects back from my .dat file. I believe they're writing properly. I feel like the solution is pretty easy, but I've been banging my head against the wall for hours over this. Neither methods are throwing any errors. If I run the save2 method, my output is this:
Obj written: [Faculty] Professor John Example [x] 123-010-1010 [x] ID: 1 [x] Salary: $63,605.00
Obj written: [Student] Ron Doe [x] 123-222-2332 [x] Major: Culinary [x] ID: 2 [x] GPA: 3.7 [x] courseBag
Obj written: [Student] Bon Jovi [x] 123-372-4383 [x] Major: Computer Science [x] ID: 3 [x] GPA: 2.85 [x] courseBag
This is the output of running the load2 method:
FOUND A STUDENT---------
[PeopleBag]: Loaded people_bag2.dat into memory successfully.
But the objects aren't getting placed into memory. There's 1 faculty and 2 students that were saved. The load method isn't even picking up the faculty member.
Here's my save method:
public void save2() {
String fileName;
FileOutputStream outFile;
ObjectOutputStream outStream;
Person tempPerson;
fileName = "people_bag2.dat";
try {
outFile = new FileOutputStream(fileName);
outStream = new ObjectOutputStream(outFile);
for (int i = 0; i < personArray.length; i++) {
if(personArray[i] != null) {
tempPerson = personArray[i];
outStream.writeObject(tempPerson); // this one line writes an object
if(Utilities.DEBUG)
System.out.println("Obj written: "+tempPerson);
}
}
outStream.close();
if(Utilities.DEBUG)
System.out.println("[PeopleBag]: Saved bag to "+fileName+" successfully.");
} catch (IOException e) {
System.out.println(e);
}
}
Here's my load method:
public void load2() {
String fileName;
FileInputStream inFile;
ObjectInputStream inStream = null;
Student tempStudent;
Faculty tempFaculty;
fileName = "people_bag2.dat";
try {
inFile = new FileInputStream(fileName);
inStream = new ObjectInputStream(inFile);
while (true) {
if(inStream.readObject().toString().startsWith("[Student")) {
System.out.println("FOUND A STUDENT---------");
tempStudent = (Student) inStream.readObject();
Student person = new Student(tempStudent.getFirstName(), tempStudent.getLastName(), tempStudent.getPhoneNumber(), tempStudent.getMajor(), tempStudent.getCourseBag());
add(tempStudent); //add(person) doesn't work either
//if(Utilities.DEBUG)
System.out.println("tempStudent: "+tempStudent.toString() + "\n");
}
if(inStream.readObject().toString().startsWith("[Faculty")) {
System.out.println("FOUND A FACULTY---------");
tempFaculty = (Faculty) inStream.readObject();
//String firstName, String lastName, String phoneNumber, String title, double salary
Faculty f = new Faculty(tempFaculty.getFirstName(), tempFaculty.getLastName(), tempFaculty.getPhoneNumber(), tempFaculty.getTitle(), tempFaculty.getSalary());
add(f); //add the person to the bag
}
}
} catch (EOFException e) { // catch EOF
try {
if(Utilities.DEBUG)
System.out.println("[PeopleBag]: Loaded "+fileName+" into memory successfully.");
inStream.close();
} exceptions blah blah
}
Also he add(Person... person) method works fine. I have a working method which loads the data from a text file. I have a similar method to load courses, except without the inStream.readObject().toString... if-statement, and it works fine. I think the issue has to do with the inStream.readObject().toString().startsWith( faculty or student).
This is a load method for courses, which works fine:
public void load() {
String fileName = "course_bag.dat";
FileInputStream inFile;
ObjectInputStream inStream = null;
Course tempCourse;
try {
inFile = new FileInputStream(fileName);
inStream = new ObjectInputStream(inFile);
while (true) {
tempCourse = (Course)inStream.readObject();
//String courseTitle, String crn, Textbook textbook, double credits
Course txtbk = new Course(tempCourse.getCourseTitle(), tempCourse.getCrn(), tempCourse.getTextbook(), tempCourse.getCredits());
add(txtbk);
}
} catch (FileNotFoundException e) {
System.out.println("File named "+ fileName +" not found.\n");
} catch (EOFException e) { // catch EOF
try {
if(Utilities.DEBUG)
System.out.println("[CourseBag]: Loaded "+fileName+" into memory successfully.");
inStream.close();
} catch (IOException ex) { }
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
}
}
Instead of reading an object and converting it to a string and throwing it away and seeing what the string starts with and then reading another object, you should read one object and use instanceof to see what it actually was.

Cannot be cast to java.util.ArrayList

Trying to write an object to an array and then save to output.data, then read the objects again.
Writing:
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("output.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(arr);
JOptionPane.showMessageDialog(null, "File Written Successfully");
oStream.close();
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
Reading:
private void readBtnActionPerformed(java.awt.event.ActionEvent evt) {
File inFile;
FileInputStream fStream;
ObjectInputStream oStream;
try {
inFile = new File("output.data");
fStream = new FileInputStream(inFile);
oStream = new ObjectInputStream(fStream);
//create an array of assessments
ArrayList <Assessment> xList;
xList = (ArrayList<Assessment>)oStream.readObject();
for (Assessment x:xList) {
JOptionPane.showMessageDialog(null, "Name: " + x.getName() + "Type: " + x.getType() + "Weighting: " + x.getWeighting());
}
oStream.close();
} catch (IOException e) {
System.out.println("Error: " + e);
} catch (ClassNotFoundException ex) {
System.out.println("Error: " + ex);
}
}
The code comppiles just fine, and the file itself saves alright too. But when I try to read the file nothing happens, and NetBeans says
"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Lnetbeansswingexample.Assessment; cannot be cast to java.util.ArrayList"
the line of code giving trouble seems to be
xList = (ArrayList<Assessment>)oStream.readObject();
Any help would be really appreciated, thanks. Sorry if the answers obvious, pretty new to programming.
Based on the exception you got, it looks like oStream.readObject() returns an array of Assessment, not a List. You can convert it to a List:
List <Assessment> xList;
xList = Arrays.asList((Assessment[])oStream.readObject());
or if you must use a java.util.ArrayList :
ArrayList<Assessment> xList;
xList = new ArrayList<> (Arrays.asList((Assessment[])oStream.readObject()));

Object Serialization and Deserialization using ArrayList in Java

I am trying to serialize an object array and write it to a file named address.ser and then read back from the file, deserialize the object array and display its attributes. I tried serializing the whole arrayList at once(deserializing it in a single session while reading) and also tried serializing each object of the object array one by one(deserializing it one by one while reading). The problem is, while reading back from the address.ser file I am getting data only of the last object which was written and none other.
Here is the code snippet:
Employee[] a=new Employee[5];
List<Employee> arr=new ArrayList<Employee>();
for(int i=0;i<=4;i++)
{
a[i]=new Employee();
System.out.println("Enter name,age,height,weight,house_no:");
a[i].name=sc.next();
a[i].age=sc.nextInt();
a[i].height=sc.nextDouble();
a[i].weight=sc.nextDouble();
a[i].house_no=sc.nextInt();
arr.add(a[i]);
}
This is the code snippet for writing objects to address.ser:
for(int i=0;i<=4;i++)
{
try
{
fout = new FileOutputStream("e:\\address.ser");
oos = new ObjectOutputStream(fout);
oos.writeObject(a[i]);
//oos.writeChars("\n");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
oos.close();
fout.close();
}
}
This is the code snippet for reading objects from address.ser:
List<Employee> recordList=new ArrayList<Employee>();
for(int i=0;i<=4;i++)
{
try
{
file = new FileInputStream("e:\\address.ser");
input = new ObjectInputStream (file);
//deserialize the List
Employee readCase=(Employee) input.readObject();
recordList.add(readCase);
System.out.print("Employee "+i+" ");
System.out.print((recordList.get(i).name)+" ");
System.out.print((recordList.get(i).age)+" ");
System.out.print((recordList.get(i).height)+" ");
System.out.print((recordList.get(i).weight)+" ");
System.out.print((recordList.get(i).house_no)+" ");
System.out.println();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
file.close();
input.close();
}
}
The final output being:
This is the way to do,
public class Test {
public static void main(String[] args) {
Employee employee=new Employee("jhon");
Employee employee2=new Employee("jojo");
Employee employee3=new Employee("albin");
ArrayList<Employee> list=new ArrayList<Employee>();
list.add(employee);
list.add(employee2);
list.add(employee3);
try {
FileOutputStream outputStream=new FileOutputStream("add.ser");
ObjectOutputStream objectOutputStream= new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(list);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream inputStream=new FileInputStream("add.ser");
ObjectInputStream objectInputStream =new ObjectInputStream(inputStream);
ArrayList<Employee> list2=(ArrayList<Employee>) objectInputStream.readObject();
for (Employee employee4 : list2) {
System.out.println(employee4.getName());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
The problem is you are trying to write the object in a wrong way. You are writing each element of the ArrayList in a same file. So what is happening is a new element is replacing the old one. So write the whole List at a time liek
oos.writeObject(yourList);
Corrected Solution
You're overwriting the file for each element you attempt to serialize. Therefore, the last serialized element remains. A file of serialized data has a header, so you must write your data in one shot.
fout = new FileOutputStream("e:\\address.ser");
oos = new ObjectOutputStream(fout);
for(int i=0;i<=4;i++)
{
try
{
oos.writeObject(a[i]);
}catch(Exception e){}
}
However, it's more efficient to serialize the entire list in one shot.

Categories

Resources