每次在 java 中创建自定义类对象数据模型时,如何将它保存到不同的文件中?



我有一个自定义列表视图,它使用对象类作为其数据。用户可以将新项目添加到列表视图中,然后将数组列表保存在共享首选项中。但是,我还想保存每个单独的项目,以便我可以在另一个可扩展的列表视图中使用它,如何为用户创建的每个单独项目创建一个文件,或者也许有更好的为什么要这样做?提前谢谢。下面是对象类:

public class Item implements Serializable{
String homework, date, classes;
public Item(String homework, String date, String classes){
this.homework = homework;
this.date = date;
this.classes = classes;
}
public String getHomework(){
return homework;
}
public String getDate(){
return date;
}
public String getClasses(){
return classes;
}
}

为什么不使用数据库?有一些设置,但是在初始设置之后写入/读取数据非常容易。 https://developer.android.com/training/basics/data-storage/databases.html

序列化-反序列化类的示例

public final class Serialize
{
private static final String className = Serialize.class.getName();
public static void save(Object saveThis, String serializeFileName, Context context)
{
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
if(saveThis != null)
{
fos = context.openFileOutput(serializeFileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(saveThis);
}
}
catch(Throwable t)
{
//log it
}
finally
{
if(oos != null)
{
try{oos.close();}catch(Throwable t){}
}
if(fos != null)
{
try{fos.close();}catch(Throwable t){}
}
}
}
public static Object read(String serializeFileName, Context context)
{
FileInputStream fis = null;
ObjectInputStream ois = null;
Object readThis = null;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && file.exists())
{
fis = context.openFileInput(serializeFileName);
ois = new ObjectInputStream(fis);
readThis = ois.readObject();
}
}
catch(Throwable t)
{
//log it
}
finally
{
if(ois != null)
{
try{ois.close();}catch(Throwable t){}
}
if(fis != null)
{
try{fis.close();}catch(Throwable t){}
}
}
return readThis;
}
public static boolean delete(String serializeFileName, Context context)
{
boolean deleted = false;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && (file.exists()))
{
deleted = file.delete();
}
}
catch(Throwable t)
{
//log it
}
return deleted;
}
public static boolean exist(String serializeFileName, Context context)
{
boolean exist = false;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && (file.exists()))
{
exist = true;
}
}
catch(Throwable t)
{
//log it
}
return exist;
}
}

使用save方法将可序列化对象保存在文件中,并使用read方法读取它。

最新更新