【问题标题】:How to save object in Java ? Deserialization in constructor如何在 Java 中保存对象?构造函数中的反序列化
【发布时间】:2017-08-11 09:01:38
【问题描述】:

我想构造一个具有以下行为的对象:

如果文件 'save_object' 为空或不存在 创建默认对象 别的 取回文件中的对象

我知道我会使用序列化How to write and read java serialized objects into a file 但是我想在课堂上做,我不知道怎么做。

我试过这段代码(对不起,我只有一部分,如果需要,我会尽快完成剩下的)

public class Garage implements Serializable
{
    private List<String> cars;

    public Garage()
    {
        File garageFile = new File("garage.txt");
        if(!garageFile.exists() || garageFile.length()==0)
        {
            cars = new List<String>;
            System.out.println("Aucune voiture sauvegardée");
        }
        else
        {
            ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(garageFile)));
            this = (Garage)ois.readObject();
         }
    }
}

this = (Garage)ois.readObject(); 有问题,我不知道如何处理。我有一些想法,但所有这些都是关于一个属性一个属性,如果可能的话,我宁愿避免这样做

【问题讨论】:

  • 我们需要的两件事:
  • 1:编译后的代码,以便我们可以在此处检查/重现内容...
  • 2:我有这个问题 = (Garage)ois.readObject(); 非常广泛...错误消息必须是也放在这里
  • @ΦXocę웃Пepeúpaツ 是的,我知道。我在工作,我没有这台电脑上的代码,所以我不能提供代码和错误信息。正如我所说,我会尽快提供所有这些。或者暂停一下,我会写一个简短的例子
  • this 是关键字,不能分配给关键字。

标签: java serialization constructor deserialization


【解决方案1】:

你的类变得复杂和错误的开发,因为你没有分割应用程序中每个模块的职责,你要做的必须是某个 GarageManager 类的工作,该类负责检查是否该文件是否存在以及为您提供一个车库对象(新创建或从磁盘恢复/反序列化)

该经理的外观示例如下:

class GarageManager {

    public static Garage GetGarage(String garagePath)
            throws FileNotFoundException, IOException, ClassNotFoundException {
        Garage x = null;
        File garageFile = new File(garagePath);
        if (!garageFile.exists() || garageFile.length() == 0) {
            ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(garageFile)));
            x = (Garage) ois.readObject();
            ois.close();
        } else {
            x = new Garage();
        }
        return x;
    }
}

【讨论】:

猜你喜欢
  • 2021-05-31
  • 1970-01-01
  • 2017-11-18
  • 2020-08-05
  • 1970-01-01
  • 2011-12-29
  • 2021-04-22
  • 1970-01-01
  • 2011-05-21
相关资源
最近更新 更多