Mallisetti Mrudhuhas
Mallisetti Mrudhuhas

Reputation: 59

saving data to a file in Java

i am working with a app which is similar to contacts app.Here i want store the data of person in a file.i have little experience with databases.I have no experience with files.So i want to work with files.I have a class

class Person
{
   String name;
   String mobile_number;
   String city;
}

Now when the user enters the data i want to store the data in a file.While retrieving i want to retrieve the data based on name or mobile or city.like i may have list of 5 persons and i want to retrieve the data of the person with particular name.So i want to know the best practices for saving and retrieving the data from a file. --Thank you

Upvotes: 2

Views: 425

Answers (2)

Akbar
Akbar

Reputation: 1

Here is sample code to store retrieved data into the file.

        try {
// Assuming the Contact bean list are taken from database and stored in list
List<ContactBean> beanList = database.getContactList();
            File file = new File(".../filpath/filename.txt");
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            for (ContactBean contactbean : beanList) {
                bw.write("name : " + contactbean.getName() + " , ");
                bw.write("mobile Number : " + contactbean.getMobileNo() + " , ");
                bw.write("city : " + contactbean.getCity() + " , ");
                bw.write("/n");
            }

            bw.close();
        } catch (Exception e) {
            e.printStrace();
        }

Upvotes: 0

Nicolas Filotto
Nicolas Filotto

Reputation: 45005

Here is an example:

public class Person implements Serializable {
    private static final long serialVersionUID = -3206878715983958638L;
    String name;
    String mobile_number;
    String city;


    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Person p = new Person();
        p.name = "foo";
        // Write
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.dat"))){
            oos.writeObject(p);
        }
        // Read
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.dat"))) {
            Person person = (Person) ois.readObject();
            System.out.println(person.name);
        }
    }
}

Upvotes: 1

Related Questions