1

DESCRIPTION:

In my program, users are asked to input some values. The values get stored into an ArrayList so that I can print them out. Now the problem with this one is all data is lost once I terminate the program. That's why I have decided to store those arrayList object into file and and read them from there.

PROBLEM/QUESTION:

I have created all the related methods to write and read file. But it seems that no objects are written and read in file.The class I am mainly concerned about is ReadWrite.

Working code:

ReadWrite:

    public void writeFile(List<PersonInfo> information) {

    try {
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(information);
        os.flush();
        fos.close();
        os.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public List<PersonInfo> readFile() {
    List<PersonInfo> dataFromFile=null;
    try {

        FileInputStream fis = new FileInputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
        ObjectInputStream is = new ObjectInputStream(fis);
        dataFromFile=(List<PersonInfo>)is.readObject();
        fis.close();
        is.close();
        //return readFile();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dataFromFile;
    }

AboutPerson:

Scanner input = new Scanner(System.in);
            List<PersonInfo> info = new ArrayList<PersonInfo>();
            List<PersonInfo> info2 = new ArrayList<PersonInfo>();
            ReadWrite rw=new ReadWrite();
            rw.writeFile(info);
            info2=rw.readFile();
            while (true) {
                System.out.println("\n");
                System.out.println("1. Input personal info\n"
                        + "2. Print them out\n"

                        + "*************"
                        + "*************");
                option1 = input.nextInt();
                input.nextLine();
                switch (option1) {
                    case 1:
                        PersonInfo personInfo = new PersonInfo();
                        //take the input
                        System.out.println("Enter a name: ");
                        personInfo.setName(input.nextLine());

                        System.out.println("Give ID: ");
                        personInfo.setId(input.nextInt());
                        System.out.println("Input credit: ");
                        personInfo.setCredit(input.nextDouble());
                        //addint them up
                        info.add(personInfo);
                        break;
                    case 2:
                        //display them 
                        System.out.println("");
                        System.out.println("Name\t\tID\t\tCredit");
                        for (PersonInfo pInfo : info) {
                            System.out.println(pInfo);
                        }
                        System.out.println("\t\t.............\n"
                                + "\t\t.............");
                        break;

        }

            }

PersonInfo:

........
........
public PersonInfo() {
        this.name = null;
        this.id = 0;
        this.credit = 0;
    }

    public void setName(String name) {
        this.name = name;
    }
.........
.........
Munira
  • 153
  • 16
  • What kind of exception do you see? Is `PersonalInfo` serializable? – AlexR Apr 28 '15 at 11:41
  • Streams should be closed in reverse order. If ObjectOutputStream needs to write something on close(), it can't as the underlying file has been closed. BTW If you use try-with-resources it will close the resource for you in the right order. – Peter Lawrey Apr 28 '15 at 11:45
  • You can replace your `os.flush(); fos.close(); os.close();` with just `os.close();`, or even better using try-with-resources. – Kayaman Apr 28 '15 at 11:45
  • AlexR, I haven't implemented any serialization and deserialization. I already have used arrayList. – Munira Apr 28 '15 at 11:48

2 Answers2

1
package com.collection;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


class PersonInfo implements Serializable{
    private String name;
    private int id;
    private double credit;
    public PersonInfo(){}
    public PersonInfo(String name,int id,int credit)
    {
        this.name=name;
        this.id=id;
        this.credit=credit;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public double getCredit() {
        return credit;
    }
    public void setCredit(double credit) {
        this.credit = credit;
    }

}
class ReadWrite
{
       public void writeFile(List<PersonInfo> information){

            try {
                FileOutputStream fos = new FileOutputStream("/home/mohammad.sadik/TestReadWrite.txt");
                ObjectOutputStream os = new ObjectOutputStream(fos);
                os.writeObject(information);
                os.flush();
                fos.close();
                os.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public List<PersonInfo> readFile() {
            List<PersonInfo> dataFromFile=null;
            try {

                FileInputStream fis = new FileInputStream("/home/mohammad.sadik/TestReadWrite.txt");
                ObjectInputStream is = new ObjectInputStream(fis);
                dataFromFile=(List<PersonInfo>)is.readObject();
                fis.close();
                is.close();
                //return readFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return dataFromFile;
            }
}
public class AboutPerson {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        List<PersonInfo> info = new ArrayList<PersonInfo>();
        List<PersonInfo> info2 = new ArrayList<PersonInfo>();
        ReadWrite rw=new ReadWrite();
        while (true) {
            System.out.println("\n");
            System.out.println("1. Input personal info\n"
                    + "2. Print them out\n"

                    + "*************"
                    + "*************");
           int option1 = input.nextInt();
            input.nextLine();
            switch (option1) {
                case 1:
                    PersonInfo personInfo = new PersonInfo();
                    //take the input
                    System.out.println("Enter a name: ");
                    personInfo.setName(input.nextLine());
                    System.out.println("Give ID: ");
                    personInfo.setId(input.nextInt());
                    System.out.println("Input credit: ");
                    personInfo.setCredit(input.nextDouble());
                    //addint them up
                    info.add(personInfo);
                    rw.writeFile(info);
                    break;
                case 2:
                    //display them 
                    info2=rw.readFile();
                    System.out.println("");
                    System.out.println("Name\t\tID\t\tCredit");
                    for (PersonInfo pinfo : info2) {
                        System.out.println(pinfo.getName()+"\t\t"+pinfo.getId()+"\t\t"+pinfo.getCredit());
                    }
                    System.out.println("\t\t.............\n"
                            + "\t\t.............");
                    break;

    }

        }
    }
}

Please implement serializable interface in PersonInf class.When u going to write object into file then u need to implement serializable interface other wise u will get exception like this: java.io.NotSerializableException: com.collection.PersonInfo

  • Mohammad Sadik, thank u so much, I will try that out soon , hope it will solve my issue. – Munira Apr 28 '15 at 13:03
  • again! I tried it, and it works for me. however, it saves objects only from the last execution. That means while running the application third time, the data from the last previous (second execution) is saved, but data written during all other previous execution(first execution) is lost. By the way, thank you for help and I got the idea. – Munira Apr 28 '15 at 16:49
0
  • first PersonInfo should implement SerialiZable,
  • and i'm not sure but PersonInfo should also have a default constructor
NDZIE Patrick Joel
  • 1,114
  • 14
  • 26