简体   繁体   中英

How do I store an arraylist?

I am trying to store my ArrayList between runtimes. So when I enter items into the ArrayList then close the program down and then open it back up and try to search the item I put in it will still be there.

I have tried MySQL and XML but I cannot figure it out. If you could please direct me in the direction of an easy way to store ArrayList that would be amazing.

Edit:

I am trying to serialize this ArrayList :

static ArrayList<Product> Chart=new ArrayList<Product>();

with these objects:

double Total;
String name;
double quantity;
String unit;
double ProductPrice;

Look into object serialization, it sounds like exactly what you want

What is object serialization?

This allows you to write a Java object to a file and read it back in later.

Here is an example. It also zips up the file, although you don't have to do that. You can also use the stream to write to a MYSQL blob instead of a file.

public static <T> void writeToGZIP(String filename, T obj) {
    ObjectOutputStream os = null;

    try {
        os = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(filename)));
        os.writeObject(obj);                    
        System.out.println("Object written to " + filename);
    } catch (Exception e) {         
        e.printStackTrace();            
    } finally {
        try {
            if (os != null) { os.flush(); os.close(); }
        } catch (IOException e) {           
            e.printStackTrace();
        }
    }       
}

@SuppressWarnings("unchecked")
public static <T> T readFromGZIP(String filename, T obj) {      
    ObjectInputStream ois = null;       

    try {
        ois = new ObjectInputStream(new GZIPInputStream(new FileInputStream(filename)));            
        obj = (T) ois.readObject();         
    } catch (Exception e) {         
        e.printStackTrace();            
    } finally { 
        try {
            if( ois != null ) ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return obj;
}

ObjectOutputStream和ObjectInputStream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM