Java 如何从文件中读取和重写单例对象? 公共类存储实现了可序列化{ /** * */ 私有静态最终长serialVersionUID=1L; public static List MessageList=Collections.synchronizedList(new ArrayList());//如果多个线程修改它们,则会确保其安全。 public static List GroupList=Collections.synchronizedList(new ArrayList()); 受保护存储(){ 超级(); } 静态私有存储_实例=null; //初始化:Storage.instance(); 静态公共存储实例(){ if(_instance==null){ _实例=新存储(); } 返回_实例; } }

Java 如何从文件中读取和重写单例对象? 公共类存储实现了可序列化{ /** * */ 私有静态最终长serialVersionUID=1L; public static List MessageList=Collections.synchronizedList(new ArrayList());//如果多个线程修改它们,则会确保其安全。 public static List GroupList=Collections.synchronizedList(new ArrayList()); 受保护存储(){ 超级(); } 静态私有存储_实例=null; //初始化:Storage.instance(); 静态公共存储实例(){ if(_instance==null){ _实例=新存储(); } 返回_实例; } },java,file,list,object,singleton,Java,File,List,Object,Singleton,我有一个创建单个对象的上层类。我想将此对象及其列表保存到文件中。然后,当我的应用程序启动并实例化存储时,我希望它读取文件,如果文件为空,则创建一个新存储,如果不是,则读取以前的存储实例,并基于旧的存储实例创建此新存储。基本上意味着我希望GroupList和MessageList的内容是持久的 编辑:因为我说得不够清楚 我应该将检查和读取该类以前的实例所需的代码放在哪里?我猜是在构造函数中,但是我的列表也会得到另一个对象的值吗?我不知道在哪里/如何编码 EDIT2:粘贴解决方案 public cl

我有一个创建单个对象的上层类。我想将此对象及其列表保存到文件中。然后,当我的应用程序启动并实例化存储时,我希望它读取文件,如果文件为空,则创建一个新存储,如果不是,则读取以前的存储实例,并基于旧的存储实例创建此新存储。基本上意味着我希望GroupList和MessageList的内容是持久的

编辑:因为我说得不够清楚

我应该将检查和读取该类以前的实例所需的代码放在哪里?我猜是在构造函数中,但是我的列表也会得到另一个对象的值吗?我不知道在哪里/如何编码

EDIT2:粘贴解决方案

public class Storage implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public static List<Message> MessageList = Collections.synchronizedList(new ArrayList<Message>()); //Fail safe if multiple threads modify them.
    public static List<Group> GroupList = Collections.synchronizedList(new ArrayList<Group>());

    protected Storage() {
        super();
    }

    static private Storage _instance = null;

    //initialized: Storage.instance();
    static public Storage instance() {
        if(_instance == null) {
            _instance = new Storage();
        }
     return _instance;
    }



}
公共类存储实现了可序列化{
/**
* 
*/
私有静态最终长serialVersionUID=1L;
public static List MessageList=Collections.synchronizedList(new ArrayList());//如果多个线程修改它们,则会确保其安全。
public static List GroupList=Collections.synchronizedList(new ArrayList());
受保护存储(){
超级();
}
静态私有存储_实例=null;
//初始化:Storage.instance();
公共静态同步存储实例(){
初始化();
if(_instance==null){
_实例=新存储();
}
返回_实例;
}
公共静态同步的void persist(){
FileOutputStream=null;
ObjectOutputStream out=null;
试一试{
fos=新文件输出流(“Storage.txt”);
out=新对象输出流(fos);
writeObject(instance());
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
out.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
受保护的静态同步void initialize(){
FileInputStream fis=null;
ObjectInputStream in=null;
试一试{
fis=新文件输入流(“Storage.txt”);
in=新的ObjectInputStream(fis);
_.readObject()中的实例=(存储);
}catch(classnotfounde异常){
e、 printStackTrace();
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(可选数据异常e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
in.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
公共静态同步无效添加元素(消息){
如果(!MessageList.contains(message)){
MessageList.add(消息);
坚持();
Log.i(“存储添加元素”,“添加:”+消息);
}
}
公共静态同步无效加法器(组){
如果(!GroupList.contains(组)){
GroupList.add(组);
坚持();
Log.i(“存储添加元素”,“添加:”+组);
}
}
公共静态同步的void removelement(消息){
如果(!MessageList.contains(message)){
MessageList.remove(消息);
坚持();
Log.i(“存储删除”,“删除:+消息”);
}
}
公共静态同步的void removelement(组){
如果(!GroupList.contains(组)){
组列表。删除(组);
坚持();
Log.i(“存储移除元素”,“移除:+组”);
}
}
公共静态同步的void wipeAll(){
MessageList.clear();
GroupList.clear();
坚持();
Log.i(“存储擦除所有”、“擦除所有数据”);
}
}

谢谢你的帮助!:)

可以通过在应用程序的主方法中读取对象并在靠近关闭点的主方法中再次保存来完成。也许我错过了什么

我假设您的实际存储类中存在为存储对象设置成员数据的代码。有鉴于此,我将推荐以下内容:

public class Storage implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public static List<Message> MessageList = Collections.synchronizedList(new ArrayList<Message>()); //Fail safe if multiple threads modify them.
    public static List<Group> GroupList = Collections.synchronizedList(new ArrayList<Group>());

    protected Storage() {
        super();
    }

    static private Storage _instance = null;

    //initialized: Storage.instance();
    public static synchronized Storage instance(){
        initialize();
        if(_instance == null) {
            _instance = new Storage();
        }
        return _instance;
    }

    public static synchronized void persist(){
        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        try{
            fos = new FileOutputStream("Storage.txt");
            out = new ObjectOutputStream(fos);
            out.writeObject(instance());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    protected static synchronized void initialize(){
        FileInputStream fis = null;
        ObjectInputStream in = null;
        try{
            fis = new FileInputStream("Storage.txt");
            in = new ObjectInputStream(fis);
            _instance = (Storage)in.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (OptionalDataException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static synchronized void addElement(Message message){
        if(!MessageList.contains(message)){
            MessageList.add(message);
            persist();
            Log.i("STORAGE-addElement", "Added: " + message);
        }
    }

    public static synchronized void addElement(Group group){
        if(!GroupList.contains(group)){
            GroupList.add(group);
            persist();
            Log.i("STORAGE-addElement", "Added: " + group);
        }
    }

    public static synchronized void removeElement(Message message){
        if(!MessageList.contains(message)){
            MessageList.remove(message);
            persist();
            Log.i("STORAGE-removeElement", "Removed: " + message);
        }
    }

    public static synchronized void removeElement(Group group){
        if(!GroupList.contains(group)){
            GroupList.remove(group);
            persist();
            Log.i("STORAGE-removeElement", "Removed: " + group);
        }
    }

    public static synchronized void wipeAll(){
        MessageList.clear();
        GroupList.clear();
        persist();
        Log.i("STORAGE-wipeAll", "Wiped all data");
    }

}

显然,您需要将序列化的单例存储在文件系统中,因此需要一个规范位置,例如,文件名的配置参数

然后,实例访问器方法有效地负责对持久实例进行编组/解编组。这是最简单的部分。(对于一个健壮的系统来说,有一小罐蠕虫:您需要确保没有其他进程写入此文件,例如,如果出现另一个JVM实例并使用相同的单例类。同样,序列化文件的名称是解决此问题的简单机制


在操作上,对实例(在mem中)的任何更改都需要与持久形式同步,例如,一致性要求将需要某种事务语义。最简单(但效率最低)只需在单例实例上的每个变异操作上将实例刷新到序列化文件中,例如,在修改列表内容时。

您可以将以下方法添加到
static public Storage instance() {
    if(_instance != null) {
        return _instance;
    }

    _instance = new Storage();

    if (file.exists()) {
         deserialize_Storage_data_from_file();
    }

    return _instance;
}
public void persist() throws IOException{

  FileOutputStream fos = null;
  ObjectOutputStream out = null;
  try{
   fos = new FileOutputStream(FILE_NAME); //assumes filename is a constant you've defined
   out = new ObjectOutputStream(fos);
   out.writeObject(time);
  }finally{
    out.close();
  }
}



protected static void initialize() throws IOException{
   FileInputStream fis = null;
   ObjectInputStream in = null;
   try{
     fis = new FileInputStream(FILE_NAME);
     in = new ObjectInputStream(fis);
     instance  = (PersistentTime)in.readObject();
   }finally{
     in.close();
   }
}
private void writeObject(ObjectOutputStream out) throws IOException
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException