简体   繁体   中英

How to make a Java array retain added objects even after terminating

I have a project that would require that I have an array that frequently has new strings added to it, and in order for the full idea to work, I need it to automatically retain the new strings even after the project ends. I work in netbeans for the most part, so is there a single line of code or some kind of method that I can use to make it so that every newly added object in an array stays in the array after the project ends, as a kind of automatic "save changes"?

You could create a wrapper for the ArrayList add method in your class which writes to a file when the add method is called and then never directly call the ArrayList add() method;

public void add(String value){
    // Write to file here - perhaps use the PrintWriter class
    list.add(value); // Then add the string to the list
}

Here is a link to the PrintWriter API which would help you get started - http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html

You will need to ensure the file you write to exists otherwise you will get a FileNotFoundException . A bit of research and you will find out how to do this.

Then you would also need to initialize the list in your constructor from the values held in your file.

Another alternative is to read and write the Strings to a database, for some insight into that look up JDBC.

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