2014-01-22 79 views
0

我知道使用File class,我可以将数据存储在硬盘上的变量中,然后再检索它们。 但是有没有什么办法可以存储一个对象,该对象有一些变量 和方法,稍后使用该对象。如何存储一个类的对象?

假设类ClassA和ClassB的两类游戏的:

public class classA{ 
    public int x,y,Vx,Vy ; 
    public void move(){ 
    x +=Vx ; 
    y +=Vy ; 

} ... }

public claassB{ 
    classA c = new classA(); 

    while(1){ 

    c.move() ; 
} 

} 
现在

让我们说,我点击保存按钮,并关闭游戏我通过点击加载按钮重新运行并加载游戏

所以有什么办法可以存储“C”,所以当我加载游戏。存储的对象将被检索并且游戏将从我离开的地方继续。 实际上不是存储我想存储对象的对象的变量。 所以我可以传递对象到classB(点击加载按钮后)。

+3

查找 “序列化” 的consept。有成千上万的方法来做到这一点。 'ObjectOutputStream'和'JSON'也是很好的关键词,可以在你的搜索中结合使用。 – zapl

+0

非常不清楚的问题 – Dima

+0

请注意,您只能序列化数据而不是代码,即'来自具有某些变量和方法的类的对象'不起作用,只是这些变量的值可能会被序列化。 – Thomas

回答

3

您可以使用序列化序列化你的对象 - Java提供了一个机制,称为对象序列化,其中一个对象可以表示为一个字节序列,其中包括对象的数据,以及有关该对象的类型和种类数据存储在对象中。 这是一个很好的例子。

public class Employee implements java.io.Serializable 
{ 
    public String name; 
    public String address; 
    public transient int SSN; 
    public int number; 
    public void mailCheck() 
    { 
     System.out.println("Mailing a check to " + name 
          + " " + address); 
    } 
} 

这里展示了如何使用:

import java.io.*; 

public class SerializeDemo 
{ 
    public static void main(String [] args) 
    { 
     Employee e = new Employee(); 
     e.name = "Reyan Ali"; 
     e.address = "Phokka Kuan, Ambehta Peer"; 
     e.SSN = 11122333; 
     e.number = 101; 
     try 
     { 
     FileOutputStream fileOut = 
     new FileOutputStream("/tmp/employee.ser"); 
     ObjectOutputStream out = new ObjectOutputStream(fileOut); 
     out.writeObject(e); 
     out.close(); 
     fileOut.close(); 
     System.out.printf("Serialized data is saved in /tmp/employee.ser"); 
     }catch(IOException i) 
     { 
      i.printStackTrace(); 
     } 
    } 
} 

检查文档,以获得更多的informations.Maybe您发现该序列是在你的情况

来源例子,以正确的方式去: Tutorialspoint

+1

你也可以使用['Externalizable'](http://docs.oracle.com/javase/7/docs/api /java/io/Externalizable.html)接口,如果你想自定义序列化。 –

0
public final static void writeObject(Object x,String name) throws IOException{ 


    try 
     { 

      FileOutputStream fileOut = new FileOutputStream(name+".ser"); 
      ObjectOutputStream out = new ObjectOutputStream(fileOut); 
      out.writeObject(x); 
      out.close(); 
      fileOut.close(); 
     }catch(IOException i) 
     { 
      i.printStackTrace(); 
     }} 


public final static Object readObject(String filename) throws IOException, ClassNotFoundException{ 

    ArrayList oldlist = null; 

     try 
     { 
      FileInputStream fileIn = new FileInputStream(filename); 
      ObjectInputStream in = new ObjectInputStream(fileIn); 
      oldlist = (ArrayList) in.readObject(); 
      in.close(); 
      fileIn.close(); 
      return oldlist; 
     }catch(IOException i) 
     { 

      writeObject(list, "list"); 
      update_list(current_link); 
      System.exit(0); 
      //i.printStackTrace(); 

       return 0;  
     }catch(ClassNotFoundException c) 
     { 

      c.printStackTrace(); 
      return null; 
     }} 
相关问题