How to make ObjectInputStream read all objects from file in java? - java

I have a file which is storing objects and I have a *getAll() method which needs to return the List<Secretary>. But, I only see single object being printed in console.
I searched for the problem and tried 3 ways but it did not work.
The insert method for inserting object in file is:
#Override
public Secretary insert(Secretary t) {
try {
System.out.println("insert called");
FileOutputStream file = new FileOutputStream
(filename,true);
ObjectOutputStream out = new ObjectOutputStream
(file);
Method for serialization of object
out.writeObject(t);
out.close();
file.close();
return t;
}
catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
I have declared append mode as true as, my file was being replaced by new object when saving.
So,i need to fetch all object from file and need to assign to a list.I tried:
public class SecretaryDaoImpl implements SecretaryDAO{
private String filename = "secretary.txt";
private Secretary sec=null;
#Override
public List<Secretary> getAll() {
//Method 1
try {
Reading the object from a file
FileInputStream file = new FileInputStream
(filename);
ObjectInputStream in = new ObjectInputStream
(file);
List<Secretary> secList=new ArrayList<>();
Method for deserialization of object
secList.add((Secretary)in.readObject());
in.close();
file.close();
System.out.println("Object has been deserialized\n"
+ "Data after Deserialization.");
System.out.println("secList is" +secList);
return secList;
}
catch (IOException ex) {
System.out.println("Secreatary file not found");
return null;
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" +
" is caught");
}
return null;
//Method 2
List<Secretary> secList=new ArrayList<>();
ObjectInputStream objectinputstream = null;
try {
FileInputStream streamIn = new FileInputStream(filename);
objectinputstream = new ObjectInputStream(streamIn);
List<Secretary> readCase = (List<Secretary>) objectinputstream.readObject();
for(Secretary s:readCase){
secList.add(s);
}
System.out.println("seclist is" + secList);
return secList;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
try {
objectinputstream.close();
} catch (IOException ex) {
Logger.getLogger(SecretaryDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Method 3
try{
File file = new File(filename);
List<Secretary> list = new ArrayList<>();
if (file.exists()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
list.add((Secretary) ois.readObject());
}
}
System.out.println("getall is"+list);
}
catch(Exception e){
}
return null;
}
}
I have commented out my code but here while posting in stackoverflow I have uncommented all the codes.
My Secretary.java is :
package com.npsc.entity;
import java.io.Serializable;
/**
*
* #author Ashwin
*/
public class Secretary implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
private int id;
private String userName;
private String password;
private Branch branch;
public String getUserName() {
return userName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Secretary(String userName, String password) {
this.userName = userName;
this.password = password;
}
public Branch getBranch() {
return branch;
}
public void setBranch(Branch branch) {
this.branch = branch;
}
#Override
public String toString() {
return "Secretary{" + "id=" + id + ", userName=" + userName + ", password=" + password + ", branch=" + branch + '}';
}
}
While performing insert operation,my txt file saving objects is:
But,I am unable to read all the object and add in list.Where I am facing the problem?

You will need to store in the file, the number of Secretary objects to read back. You can then determine how many entities to read, and thus repopulate your list.
Something like:
List<Secretary> list;
private void persistList(ObjectOutputStream out) {
out.writeInt(list.size());
for (Secretary sec : list) {
out.writeObject(sec);
}
}
And then to read:
private List<Secretary> readFromStream(ObjectInputStream in) {
int numObjects = in.readInt();
List<Secretary> result = new ArrayList<>(numObjects);
for (int i = 0; i < numObjects; i++) {
result.add((Secretary)in.readObject());
}
return result;
}
This is just a sketch of the technique (and ignores error handling, stream opening/closing etc.); the main thing is to integrate the idea of recording the size of the list, then reading that many Secretaries into your existing code.

Write a List<Secretary> to file and read same back, then you will have all.
write (Secretary s) {
read List<Secretary> currentList ;
currentList.add(s)
write List<Secretary>
}

Related

TableView content not showing [duplicate]

This question already has answers here:
Javafx tableview not showing data in all columns
(3 answers)
Closed 4 years ago.
I have a table view which I have populated with information, however while I can select the rows which hold data, the text is not visible. Using table.getSelectionModel().getSelectedItem(); I can confirm that the table has indeed elements inside but the text does not show up.
I have a Socket communication in my programm where the server send the client an ArrayList of elements that the Client needs to display in the TableView.
Server side:
private void acceptedConnection(Socket client, Connection con){
try(ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream())){
System.out.println("receiving request");
String table = ois.readUTF();
System.out.println("Preparing statement");
PreparedStatement getTableContent = con.prepareStatement("SELECT * from " + table);
System.out.println("Fetching results");
ResultSet tableContentRs = getTableContent.executeQuery();
Builder builder = null;
switch (table){
case "blog_user": builder = new UserBuilder();break;
}
assert builder != null;
ArrayList tableContent = builder.buildArrayList(tableContentRs);
System.out.println("Sending results");
oos.writeObject(tableContent);
oos.flush();
System.out.println("Results sent");
}catch (IOException | SQLException e){
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client side:
public void loadTableContent(){
try (Socket client = new Socket(InetAddress.getLocalHost(), 667);
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(client.getInputStream())) {
System.out.println("Sending request");
String selectedTable = databaseTableComboBox.getSelectionModel().getSelectedItem();
oos.writeUTF(selectedTable);
oos.flush();
table.getColumns().clear();
table.getItems().clear();
ArrayList data = null;
Builder builder = null;
switch (selectedTable){
case "blog_user": builder = new UserBuilder();data = (ArrayList<User>)ois.readObject();break;
}
assert builder != null;
builder.setColumns(table);
table.getItems().addAll(data);
table.refresh();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
The UserBuilder:
public class UserBuilder implements Builder {
#Override
public ArrayList buildArrayList(ResultSet set) throws SQLException {
ArrayList<User> users = new ArrayList<>();
while (set.next()) users.add(new User(set.getInt(1), set.getString(2), set.getString(3)));
return users;
}
#Override
public void setColumns(TableView table) {
TableColumn<User, String> idCol = new TableColumn<>("ID");
TableColumn<User, String> nameCol = new TableColumn<>("Name");
TableColumn<User, String> pwdCol = new TableColumn<>("Passwort");
idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
nameCol.setCellValueFactory(new PropertyValueFactory<>("username"));
pwdCol.setCellValueFactory(new PropertyValueFactory<>("pwd"));
table.getColumns().addAll(idCol, nameCol, pwdCol);
}
}
And the User:
public class User implements Serializable{
private int id;
private String username;
private String pwd;
public User(int id, String username, String pwd) {
this.id = id;
this.username = username;
this.pwd = pwd;
}
#Override
public String toString() {
return id + " " + username + " " + pwd;
}
}
The interesting thing is that it already worked once but then I added the same mechanism I had for User and UserBuilder for other classes (so e.g. Admin and AdminBuilder) and suddenly the text did not show up in the TableView anymore.
Any and all help is greatly appreciated.
Your User class needs getter methods. The PropertyValueFactory needs to access these fields.
public class User {
private final int id;
private final String username;
private final String pwd;
public User(int id, String username, String pwd) {
this.id = id;
this.username = username;
this.pwd = pwd;
}
#Override
public String toString() {
return id + " " + username + " " + pwd;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPwd() {
return pwd;
}
}

Writing and Reading to/from a file Objects stored in ArrayList

This is a simple example where I'm trying to write and read Objects stored in ArrayList to/from file.
Writing file is working. Reading file is working only for first Object in my ArrayList. How should I make this into a loop?
I tried with something like:
`while(ois !=null) {
Person result = (Person) ois.readObject();
persons.add(result);
}
but it's not working.
Here is full test code:
public class Data {
static ArrayList<Person> persons = new ArrayList<Person>();
public static void savePersons() throws IOException{
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object for examle */
for(int i = 0; i<5; i++){
Person personTest = new Person("name", "surname", "email", "1234567890");
persons.add(personTest);
}
try{
fout = new FileOutputStream("C:\\data.dat", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
System.out.println("Saving '" +persons.size()+ "' Object to Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR");
} finally {
if(oos != null){
oos.close();
}
}
}
public static void loadPersons() throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
/** Clean 'persons' array for TEST of load data*/
persons.removeAll(persons);
try {
fis = new FileInputStream("C:\\data.dat");
ois = new ObjectInputStream(fis);
Person result = (Person) ois.readObject();
persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" +persons.size()+ "' Object from Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("loadPersons() = OK");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR");
} finally {
if(ois != null){
ois .close();
}
}
}
}
Person class:
public class Person implements Serializable {
private String name;
private String surname;
private String mail;
private String telephone;
Person person;
public Person(String n, String s, String m, String t){
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}}
Main class:
public class Test {
public static void main(String[] args) {
Data.savePersons();
Data.loadPersons();
}}
Here you go... please take note of the following:
YES, Chetan Jadhav CD's suggestion WORKS. B
Use an IDE like Eclipse to help you debug your code and make your life easier.
Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:
System.out.println("Saving ERROR: " + ex.getMessage());
Put all your code in one file before you ask for help to make everyone's life easier.
Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Data {
private static final String SER_FILE = "C:\\view\\data.ser";
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons();
Data.loadPersons();
}
public static void savePersons() throws IOException {
/** Make 5 'Person' object for example */
for (int i = 0; i < 5; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
persons.add(personTest);
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
}
}
public static void loadPersons() throws IOException {
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
persons.stream().forEach(System.out::println);
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
}
}
}
class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}
#Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
}
}

Java Streams read files and print objects read on files

So guys i need some help. I have a class Book and i want to save my books object to a Stream and then read this Stream file so i can search my objects from there. I have written my code but it gives me some errors and i can figure out how to print my books values .
So this is my Book class
public class Book {
private Date arr;
private Date depp;
private Type room;
private boolean breakfast = false;
private Person data;
private ObjectOutputStream out;
public Book(String name, String surename, String phone,Date arr, Date depp, Type room, boolean breakfast) {
data = new Person(name,surename,phone);
this.arr = arr;
this.depp = depp;
this.room = room;
this.breakfast = breakfast;
}
public void writeObjToFile(){//here i save my object to stream it gives me error, i call this method after i create my book object to main
try{
out = new ObjectOutputStream(new FileOutputStream("books.txt"));
out.writeObject(this);
}
catch(FileNotFoundException e){
System.err.println("File not Found");
e.printStackTrace();
}catch(IOException e){
System.err.println("IOException");
e.printStackTrace();}
}
}
and this is my Search class :
public class Search {
private FileInputStream fis=null;
private String filename;
public Search(String filename){
this.filename = filename;
File file = new File(filename);
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Book should implement Serializable
Check the API
https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeObject%28java.lang.Object%29
Also, remove the out member from Book class because it's not Serializable either.

Android readObject exception, cannot cast String to ObjectStreamClass

I am working on an android project that loads data remotely, saves it into an array (if the data is new), writes it to disk as a serializeable, then reads it from disk to load an ArrayList.
Sometimes the ArrayList populates with the data, sometimes it doesn't and the program crashes.
I receive a runtime exception stating: java.land.ClassCastException: java.lang.String cannot be cast to java.io.ObjectStreamClass.
Sometimes I also receive a java.io.StreamCorruptedException, and sometimes I receive and EOFException.
Going through the exception tree, it seems to be originating from this call:
personsArray = (ArrayList<Person>) in.readObject();
Now, sometimes the data loads fine without issues, most of the time the program crashes.
Here is the code that saves the data to disk:
public static boolean saveFromRemoteSource(Context c, ArrayList<?> source){
//Save context
context = c;
//Save source to local file
File file = context.getFileStreamPath(PERSONS_FILE);
//Status if successful in saving
boolean savedStatus = false;
try {
if(!file.exists()){
file.createNewFile();
}else{
//file already exists so don't do anything
}
//now load the data into the file
FileOutputStream fos = context.openFileOutput(PERSONS_FILE, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(source);
oos.close();
savedStatus = true;
} catch(IOException e){
e.printStackTrace();
savedStatus = false;
}
return savedStatus;
}
Here is the code that reads the data from disk:
public static boolean loadPersonsArray(Context c){
context = c;
boolean loadStatus = false;
File file = context.getFileStreamPath(PERSONS_FILE);
try{
if(!file.exists()){
file.createNewFile();
}else {
//File is already created, do nothing
}
BufferedReader br = new BufferedReader(new FileReader(file));
if (br.readLine() != null) {
FileInputStream fis = context.openFileInput(PERSONS_FILE);
ObjectInputStream in = new ObjectInputStream(fis);
personsArray = (ArrayList<Person>) in.readObject();
in.close();
fis.close();
loadStatus = true;
}
br.close();
} catch(IOException e){
e.printStackTrace();
Log.d("TAG", "IOException PERSONS_FILE file: " + e);
loadStatus = false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d("TAG", "ClassNotFoundException PERSONS_FILE file classnotfound: " + e);
}
return loadStatus;
}
This is the Person class:
import java.io.Serializable;
public class Person implements Serializable, Comparable<Person>{
//Person class
private static final long serialVersionUID = 1L;
private String personID;
private String personName;
private boolean displayPerson;
//default constructor
public Person(){
super();
}
public Person(String personID,
String personName,
boolean displayPerson){
super();
this.personID = personID;
this.personName = personName;
this.displayPerson = displayPerson;
}
//Accessor Methods
public String getPersonID(){
return personID;
}
public String getPersonName(){
return personName;
}
public boolean getDisplayPerson(){
return displayPerson;
}
//setter methods
public void setPersonID(String personID){
this.personID = personID;
}
public void setPersonName(String personName){
this.personName = personName;
}
public void setDisplayPerson(boolean displayPerson){
this.displayPerson = displayPerson;
}
#Override
public String toString(){
return this.getPersonName().replaceAll("[^A-Za-z0-9]", "") + this.getDisplayPerson();
}
public int compareTo(Person otherPerson) {
if(!(otherPerson instanceof Person)){
throw new ClassCastException("Not a valid Person object!");
}
Person tempPerson = (Person)otherPerson;
if(this.getPersonName().compareToIgnoreCase(tempPerson.getPersonName()) > 0){
return 1;
}else if(this.getPersonName().compareToIgnoreCase(tempPerson.getPersonName()) < 0){
return -1;
}else{
return 0;
}
}
}
Where the data comes from to be written to the file
private void downloadPersons(){
HashMap<String, String> params = new HashMap<String, String>();
Kumulos.call("selectAllPersons", params, new ResponseHandler() {
#Override
public void didCompleteWithResult(Object result) {
ArrayList<Object> personsList = new ArrayList<Object>();
for(Object o : (ArrayList<?>)result){
Person person = new Person();
person.setPersonID(replaceNandT((String) ((HashMap<?,?>) o).get("personID")));
person.setLawName(replaceNandT((String) ((HashMap<?,?>) o).get("personName")));
person.setDisplayLaw(stringToBool((String)((HashMap<?,?>) o).get("displayPerson")));
if(person.getDisplayPerson()==true){
personsList.add(person);
}
}
//Save personsList to a file
if(PersonsLoader.saveFromRemoteSource(context, personsList)){
updateVersionNumber();
isFinished=true;
Log.d("TAG", "PersonsLoader.saveFromRemoteSource(context, personsList) success");
}
}
});
}
So what do you think is happening at this call?
Get rid of both the blocks that test File.exists(), and the File.createNewFile() calls.
Opening the file for output will create it if necessary.
When opening the file for reading, if the file doesn't exist a FileNotFoundException will be thrown. There's no point in creating an empty file to avert this: it just leads to other problems.
And get rid of the BufferedReader and readLine() calls too. They serve no useful purpose. There are no lines in an object output stream.

Java: Serializing beginner problem :-(

I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.
package sotring;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.bcel.internal.generic.INEG;
public class storeing {
public static void storeMail(Message[] mail){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser"));
out.writeObject(mail);
out.flush();
out.close();
} catch (IOException e) {
}
}
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
for (int i=0; i< array.length;i++)
System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent());
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user1 = new User("User1", "geheim");
User user2 = new User("User2", "geheim");
Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar");
Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo");
Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) ");
Message [] mails = {email1, email2, email3};
storeMail(mails);
Message[] restored = getStoredMails();;
}
}
Here are the user and message class
public class Message implements Serializable{
static final long serialVersionUID = -1L;
private String receiver; //Empfänger
private String sender; //Absender
private String Betreff;
private String content;
private String timestamp;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Message (String receiver, String sender, String Betreff, String content) {
this.Betreff= Betreff;
this.receiver = receiver;
this.sender = sender;
this.content = content;
this.timestamp = getDateTime();
}
Message() { // Just for loaded msg
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getContent() {
return content;
}
public String getTime() {
return timestamp;
}
public void setContent(String content) {
this.content = content;
}
}
public class User implements Serializable{
static final long serialVersionUID = -1L;
private String username; //unique Username
private String ipadress; //changes everytime
private String password; //Password
private int unreadMsg; //Unread Messages
private static int usercount;
private boolean online;
public String getName(){
return username;
}
public boolean Status() {
return online;
}
public void setOnline() {
this.online = true;
}
public void setOffline() {
this.online = false;
}
User(String username,String password){
if (true){
this.username = username;
this.password = password;
usercount++;
} else System.out.print("Username not availiable");
}
public void changePassword(String newpassword){
password = newpassword;
}
public void setIP(String newip){
ipadress = newip;
}
public String getIP(){
if (ipadress.length() >= 7){
return ipadress;
} else return "ip address not set.";
}
public int getUnreadMsg() {
return unreadMsg;
}
}
Here is the exception:
exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type Message[]
at sotring.storeing.getStoredMails(storeing.java:22)
at sotring.storeing.main(storeing.java:57)
THANK YOU FOR YOUR HELP!!!!!!!!!!!
The catch clauses need to return something.
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null; //fix
}
If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.
Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.
On a different note, have you considered a third-party serializer library?
I'm using Simple right now for a project, and it seems to do stuff just fine with very little effort.
in the exception handling blocks of the getStoredMails method you do not return anything.
Suggested modification:
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null;
}
I modified the source. I added "return null" in exception and the for loop the output in the function. And the function gives me the right output but then throws it the exception.

Categories

Resources