0

I have an object arraylist, can someone please help me by telling me the most efficient way to write AND retrieve an object from file?

Thanks.

My attempt

 public static void LOLadd(String ab, String cd, int ef) throws IOException {
     MyShelf newS = new MyShelf();
     newS.Fbooks = ab;
     newS.Bbooks = cd;
     newS.Cbooks = ef;
     InfoList.add(newS);

         FileWriter fw;
                 fw = new FileWriter("UserInfo.out.txt");
             PrintWriter outt = new PrintWriter(eh);
                 for (int i = 0; i <InfoList.size(); i++)
                 {
                     String ax = InfoList.get(i).Fbooks;
                     String ay = InfoList.get(i).Bbooks;
                     int az = InfoList.get(i).Cbooks;
                     output.print(ax + " " + ay + " " + az);  //Output all the words to file // on the same line
                     output.println(""); //Make space
                 }
                 fw.close();
                 output.close();
}

My attempt to retrieve file. Also, after retrieving file, how can I read each column of Objects?? For example, if I have ::::: Fictions, Dramas, Plays --- How can I read, get, replace, delete, and add values to Dramas column?

public Object findUsername(String a) throws FileNotFoundException, IOException,     ClassNotFoundException  
{    
 ObjectInputStream sc = new ObjectInputStream(new FileInputStream("myShelf.out.txt"));

    //ArrayList<Object> List = new ArrayList<Object>();
    InfoList = null;
    Object  obj = (Object) sc.readObject();

    InfoList.add((UserInfo) obj);
    sc.close();

     for (int i=0; i <InfoList.size(); i++) {
          if (InfoList.get(i).user.equals(a)){
               return "something" + InfoList.get(i);
      }
   }
     return "doesn't exist"; 
 }

public static String lbooksMatching(String b)    {

    //Retrieve data from file
    //...

    for (int i=0; i<myShelf.size(); i++)       {
        if (myShelf.get(i).user.equals (b))   
        {
            return b;
        }
        else 
        {
            return "dfbgregd"; 
        }
   }
    return "dfgdfge"; 
}

public static String matching(String qp)    {
    for (int i=0; i<myShelf.size(); i++)       {
        if (myShelf.get(i).pass.equals (qp))   
        {
            return c;
        }
        else 
        {
            return "Begegne"; 
        }
   }
    return "Bdfge"; 
}

Thanks!!!

2

2 Answers 2

3

It seems like you want to serialize an object and persist that serialized form to some kind of storage (in this case a file).

2 important remarks here :

Serialization

Internal java serialization

  • Java provides automatic serialization which requires that the object be marked by implementing the java.io.Serializable interface. Implementing the interface marks the class as "okay to serialize," and Java then handles serialization internally.
  • See this post for a code sample on how to serialize / deserialize an object to/from bytes.

This might nog always be the ideal way to persist an object, as you have no control over the format (handled by java), it's not human readable, and you can versioning issues if your objects change.

Marshalling to JSON or XML

  • A better way to seralize an object to disk is to use another data format like XML or JSON.
  • A sample on how to convert an object to/from a JSON structure can be found here.

Important : I would not do the kind of serialization in code like you're doing unless there is a very good reason (that I don't see here). It quickly becomes messy and is subject to change when your objects change. I would opt for a more automated way of serializing. Also, when using a format like JSON / XML, you know that there are tons of APIs available to read/write to that format, so all of that serialization / deserialization logic doesn't need to be implemented by you anymore.

Persistence

Writing your serialized object to a file isn't always a good idea for various reasons (no versioning / concurrency issues / .....).

A better approach is to use a database. If it's a hierarchical database, take a look at Hibernate or JPA to persist your objects with very little code. If it's a document database like MongoDB, you can persist your JSON serialized representation.

There are tons of resources available on persisting objects to databases in Java. I would suggest checking out JPA, the the standard API for persistence and object/relational mapping .

Sign up to request clarification or add additional context in comments.

2 Comments

a couple of remarks regarding nomenclature: 1) Considering as serialization the transformation of an object instance into a byte array representation, I would say that Serializing to JSON or XML is marshalling, since we are transforming the object to a text representation of it, and that text representation needs to be serialized later in order to be saved to a stream. 2) MongoDB defines itself as a document database, not an object database. Good answer anyway.
Hello, since I am a beginner, I think using DB is just too complicated for me. My goal is to only write to file...
0

Here is another basic example, which will give you insight into Arraylist,constructor and writing output to file: After running this, if you are using IDE go to project folder, there you will file *.txt file.

import java.io.*;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ListOfNumbers {

    private List<Integer> list;
    private static final int SIZE = 10;//whatever size you wish

    public ListOfNumbers () {
        list = new ArrayList<Integer>(SIZE);
        for (int i = 0; i < SIZE; i++) {
            list.add(new Integer(i));
        }
    }

    public void writeList() {
        PrintWriter out = null;
        try {
            out = new PrintWriter(new FileWriter("ManOutFile.txt"));
            for (int i = 0; i < SIZE; i++) {
                out.println("Value at: " + i + " = " + list.get(i));
            }
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(ListOfNumbers.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }
public static void main(String[] args)
{
    ListOfNumbers lnum=new ListOfNumbers();
    lnum.writeList();
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.