假设自定义类为Book
public class Book{
String name;
String info;
}
将Book对象存到集合中
ArrayList<Book> bookArrayList = new ArrayList< >( );
此时若要将集合存储到本地,并进行读取,则需要对Book类实现Serializable接口
public class Book implements Serializable{
String name;
String info;
}
此时储存集合中数据到本地方法为:
public void writeList(){
try{
FileOutputStream fs=new FileOutputStream("D:/book.txt");//文件路径可以随意,若没有文件的话,需要先在程序中创建
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(bookArrayList);
os.close();
}catch(Exception e){
e.printStackTrace();
}
}
在本地中读取数据并赋值给集合方法为:
bookArrayList = readFile();
public ArrayList<Book> readFile(){
ObjectInputStream oi;
ArrayList<Book> bookArrayList =null;
try{
FileInputStream fi=new FileInputStream("D:/book.txt");
oi=new ObjectInputStream(fi);
bookArrayList=(ArrayList<Book>) oi.readObject();
oi.close();
}catch(Exception e){
e.printStackTrace();
}
return bookArrayList;
}