Where to implement onSave and onLoad functions to create serializable file - java

I've created these two functions and added them into an action listener within a button . The aim is to create a serialized file and write what is in the Jlist to the file. When the program is closed , the jlist should be populated with what is in the serialized file. For some reason it isn't working. Can anyone see what is wrong?
Here is the code:
JButton btnAdd = new JButton("Add"); // Setting what is written on the button
btnAdd.addActionListener(new ActionListener() { // implementing an action listener
public void actionPerformed(ActionEvent arg0) {
patientname = textField.getText(); // Getting the patient name from the textfield
patientaddress = textField_1.getText();
patientphone = textField_2.getText();
textField.setText(""); // Setting the textfield to be blank so that the user can input there name address etc..
textField_1.setText("");
textField_2.setText("");
patientid = patientid + 1;//Implementing the id to add 1 every time another id is added
Patient patient = new Patient(patientname, patientaddress, patientphone, patientid); // Populating the array list patientlist with the users input
patientList.add(patient); // Adding the patient's details to the patientlist
patientListModel.addElement(patient); // adds the patient's details to the list model
}
public void onSave(List<Patient> PatientList) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File("PatientList.ser")));
out.writeObject(PatientList);
out.flush();
}
catch (IOException e) {
// handle exception
}
finally {
if (out != null) {
try {
out.close();
}
catch (IOException e) {
// handle exception
}
}
}
}
public List<Patient> onLoad() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(new File("PatientList.ser")));
return (List<Patient>) in.readObject();
}
catch (IOException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
// handle exception
}
}
}
return null;
}
});
btnAdd.setBounds(0, 86, 65, 23);
contentPane.add(btnAdd);
/////////////////
Here is my patient class :
public class Patient {
public String patientName;
public String patientAddress;
public String patientPhone;
public int patientID;
public Patient(String patientname, String patientaddress, String patientphone,int patientid){
patientName = patientname;
patientAddress = patientaddress;
patientPhone = patientphone;
patientID = patientid;
}
public String setName(String patientname){
return patientName = patientname;
}
public String getName(){
return patientName;
}
public String setAddress(String patientaddress){
return patientAddress = patientaddress;
}
public String getAddress(){
return patientAddress;
}
public String setPhoneNum(String patientphone){
return patientPhone = patientphone;
}
public String getPhoneNum(){
return patientPhone;
}
public int setID(int patientid){
return patientID = patientid;
}
public int getID(){
return patientID;
}
public String toString() { // Printing the patient's details to the scroll pane
return "Patient Name: " + patientName + ", PatientAddress: "
+ patientAddress + ", PatientPhone: " + patientPhone
+ ", patientID: " + patientID +"" ;
}
}

Related

Actual and formal argument lists differ in length error in main

Im working on a project where I have 3 text files with data of doctors, patients and home visits. When Im trying to upload the doctors file, upload all the data to a new object I get an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Id_pacjenta Nazwisko Imie PESEL Data_urodzenia"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at com.company.Main.main(Main.java:40)
Below I'll paste my main as well as the classes & a snapshot of the text file used for imports:
Could anyone advise how to avoid this issue? Thanks!
public class Main {
public static void main(String[] args) {
List<Lekarz> lekarz = new ArrayList<>();
try{
File fileLekarze = new File("src/com/company/lekarze.txt");
Scanner readerLekarze = new Scanner(fileLekarze);
while(readerLekarze.hasNextLine()){
String[] data =readerLekarze.nextLine().split(" ");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
readerLekarze.close();
} catch (FileNotFoundException e) {
System.out.println("Error File Lekarze");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
List<Pacjenci> pacjent = new ArrayList<>();
try{
File pacjenciFile = new File("src/com/company/pacjenci.txt");
Scanner readerPacjenci = new Scanner(pacjenciFile);
while(readerPacjenci.hasNextLine()){
String[] data = readerPacjenci.nextLine().split(" ");
pacjent.add(new Pacjenci(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}
readerPacjenci.close();
}catch (FileNotFoundException e) {
System.out.println("Error File Pacjenci");
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
}
}
public class Pacjenci {
private int idPacjenta;
private String nazwisko;
private String imie;
private String pesel;
private Date dataUrodzenia;
public Pacjenci(int idPacjenta, String nazwisko, String imie, String pesel, Date dataUrodzenia) {
this.idPacjenta = idPacjenta;
this.nazwisko = nazwisko;
this.imie = imie;
this.pesel = pesel;
this.dataUrodzenia = dataUrodzenia;
}
public int getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(int idPacjenta) {
this.idPacjenta = idPacjenta;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public Date getDataUrodzenia() {
return dataUrodzenia;
}
public void setDataUrodzenia(Date dataUrodzenia) {
this.dataUrodzenia = dataUrodzenia;
}
#Override
public String toString() {
return "Pacjenci{" +
"idPacjenta=" + idPacjenta +
", nazwisko='" + nazwisko + '\'' +
", imie='" + imie + '\'' +
", pesel='" + pesel + '\'' +
", dataUrodzenia=" + dataUrodzenia +
", wizyty=" +
", lekarze=" +
'}';
}
}
public class Wizyty {
private Lekarz idLekarza;
private Pacjenci idPacjenta;
private Date dataWizyty;
public Wizyty(Lekarz idLekarza, Pacjenci idPacjenta, Date dataWizyty) {
this.idLekarza = idLekarza;
this.idPacjenta = idPacjenta;
this.dataWizyty = dataWizyty;
}
public Lekarz getIdLekarza() {
return idLekarza;
}
public void setIdLekarza(Lekarz idLekarza) {
this.idLekarza = idLekarza;
}
public Pacjenci getIdPacjenta() {
return idPacjenta;
}
public void setIdPacjenta(Pacjenci idPacjenta) {
this.idPacjenta = idPacjenta;
}
public Date getDataWizyty() {
return dataWizyty;
}
public void setDataWizyty(Date dataWizyty) {
this.dataWizyty = dataWizyty;
}
#Override
public String toString() {
return "Wizyty{" +
"idLekarza=" + idLekarza +
", idPacjenta=" + idPacjenta +
", dataWizyty=" + dataWizyty +
'}';
}
}
Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
100 Kowal Waldemar 01211309876 2001-1-13
Because of the data spacing in the file, try this:
while(readerLekarze.hasNextLine()){
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim()
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(Integer.parseInt(data[0]),data[1],data[2],data[3],new SimpleDateFormat("yyyy-MM-dd").parse(data[4]),data[5],data[6]));
}
You could also just do:
String[] data = readerLekarze.nextLine().trim().split("\\s+");
As a complement to the #DevilsHnd, you only need to add a code to avoid the first line, because the first line is the "header information" of your file.
boolean headerRead = false;
while(readerLekarze.hasNextLine()) {
if (!headerRead) {
// extract the first line -> Id_pacjenta Nazwisko Imie PESEL Data_urodzenia
readerLekarze.nextLine();
headerRead = true;
continue;
}
String line = readerLekarze.nextLine();
// Remove leading and trailing whitespaces (if any).
line = line.trim();
// "\\s+" Takes care of any multi-spacing within the data line when splitting.
String[] data =line.split("\\s+");
lekarz.add(new Lekarz(
Integer.parseInt(data[0]),
data[1],
data[2],
data[3],
new SimpleDateFormat("yyyy-MM-dd").parse(data[4])));
}

How to make ObjectInputStream read all objects from file in 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>
}

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;
}
}

How to get variables from exception code block

I want to get user1.name variable from public static void FileRead()to private void jButton1ActionPerformed but It doesn't read user1.name. Can you explain me how can I use that variable.
public static class Users {
public String name;
public String password;
Users(String name1, String password1) {
name = name1;
password = password1;
}
}
public static void FileRead() {
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/B_Ali/Documents/NetBeansProjects/JavaApplication20/UserNamePassword.txt"));
String[] s1 = new String[5];
String[] s2 = new String[5];
int i = 0;
while ((s1[i] = in.readLine()) != null) {
s1[i] = s2[i];
i = i + 1;
if (i == 1) {
Users user1 = new Users(s2[0], s2[1]);
}
else if (i == 3) {
Users user2 = new Users(s2[2], s2[3]);
}
else if (i == 5) {
Users user3 = new Users(s2[4], s2[5]);
}
}
in.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, user1.name);
// TODO add your handling code here:
}
where should I declare it?
Edit: if i declare it as you said before. It becomes meaningless because i want to use user1.name which is defined in FileRead().
Declare it global.
Users user1;
public static class Users {
public String name;
public String password;
Users(String name1, String password1) {
name = name1;
password = password1;
}
public String getName()
{ return this.name;
}
public String getPassword()
{return this.password;
}
}
Users user1, user2;
public static void FileRead() {
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/B_Ali/Documents/NetBeansProjects/JavaApplication20/UserNamePassword.txt"));
String[] s1 = new String[5];
String[] s2 = new String[5];
int i = 0;
while ((s1[i] = in.readLine()) != null) {
s1[i] = s2[i];
i = i + 1;
if (i == 1) {
Users user1 = new Users(s2[0], s2[1]);
}
else if (i == 3) {
Users user2 = new Users(s2[2], s2[3]);
}
else if (i == 5) {
Users user3 = new Users(s2[4], s2[5]);
}
}
in.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, user1.getName());
// TODO add your handling code here:
}
You need to declare the variables you need outside of the try clause like:
String global = null;
try{
global = "abc";
throw new Exception();
}
catch(Exception e){
if (global != null){
//your code
}
}

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