How to write and retrieve objects arraylist to file?

我只是一个虾纸丫 提交于 2020-01-07 04:36:07

问题


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!!!


回答1:


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 .




回答2:


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


来源:https://stackoverflow.com/questions/15574168/how-to-write-and-retrieve-objects-arraylist-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!