2

给定一个静态类,例如MyStaticClass,它有两种方法可以将自身保存到文件或从文件中加载,例如:

private static void save() throws IOException {
  FileOutputStream fos = new FileOutputStream(new File("myfile.dat"));
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(???);
  oos.close();
}

private static void load() throws IOException {
  FileInputStream fis = new FileInputStream(new File("myfile.dat"));
  ObjectInputStream ois = new ObjectInputStream(fis);
  ??? = (MyStaticClass) ois.readObject();
  ois.close();
}

我应该用什么代替???通常放置对象实例的位置?

有没有办法将静态类保存到与用于实例的文件不同的文件中?

4

2 回答 2

4

据我所知,你不能那样做。但是您可以单独编写静态字段,而不是一次性编写整个类。

例如。

public class MyClass() {

    private static String staticField1;
    private static String staticField2;

    static {
        load();
    }

    private static void saveField(String fieldName, Object fieldValue) throws IOException {
      FileOutputStream fos = new FileOutputStream(new File("MyClass-" + fieldName + ".dat"));
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(fieldValue);
      oos.close();
    }


    private static Object readField(String fieldName) throws IOException {
      FileInputStream fis = new FileInputStream(new File("MyClass-" + fieldName + ".dat"));
      ObjectInputStream ois = new ObjectInputStream(fis);
      Object value = ois.readObject();
      ois.close();

      return value;
    }

    private static void save() throws IOException {
      saveField("staticField1", staticField1);
      saveField("staticField2", staticField2);
    }

    private static void load() throws IOException {
      staticField1 = (String)readField("staticField1");
      staticField2 = (String)readField("staticField2");
    }

}
于 2013-03-25T16:34:17.773 回答
1

我不确定您所说的“静态类”是什么意思。如果您的意思是类的状态仅由静态数据成员组成,则将这些数据成员存储在 save() 方法中,并在 load 方法中更新它们。

另一方面,如果您想要保存非静态状态,那么看起来 save 方法不应该是静态的,而 load 方法应该是静态的,并返回一个新实例。

于 2013-03-25T16:45:08.953 回答