2012-08-12 79 views

回答

2

如果你是,你应该对象的数组序列化到一个文件一个初学者。该公约是命名您的序列化的文件名称的-file.ser

try 
     { 
    FileOutputStream fileOut = new FileOutputStream("card.ser");//creates a card serial file in output stream 
    ObjectOutputStream out = new ObjectOutputStream(fileOut);//routs an object into the output stream. 
    out.writeObject(array);// we designate our array of cards to be routed 
    out.close();// closes the data paths 
    fileOut.close();// closes the data paths 
    }catch(IOException i)//exception stuff 
    { 
     i.printStackTrace(); 
} 

到deserialze它使用:

try// If this doesnt work throw an exception 
     { 
      FileInputStream fileIn = new FileInputStream(name+".ser");// Read serial file. 
      ObjectInputStream in = new ObjectInputStream(fileIn);// input the read file. 
      object = (Object) in.readObject();// allocate it to the object file already instanciated. 
      in.close();//closes the input stream. 
      fileIn.close();//closes the file data stream. 
     }catch(IOException i)//exception stuff 
     { 
      i.printStackTrace(); 
      return; 
     }catch(ClassNotFoundException c)//more exception stuff 
     { 
      System.out.println("Error"); 
      c.printStackTrace(); 
      return; 
     } 
+0

这正是我一直在寻找的谢谢! – user1593821 2012-08-12 18:59:06

0

要序列化一个对象,创建一个ObjectOutputStream并调用writeObject。

// Write to disk with FileOutputStream 
FileOutputStream f_out = new 
    FileOutputStream("myobject.data"); 

// Write object with ObjectOutputStream 
ObjectOutputStream obj_out = new 
    ObjectOutputStream (f_out); 

// Write object out to disk 
obj_out.writeObject (myArray); 

Reference

0

可以序列多种对象。是的,一个数组也是一个对象(@see Array class)。如果你不想限制数组的限制,你也可以使用其中一个Container类(例如LinkedList)。序列化工作方式相同。

-1

编写一个管理这个数组的类。把它和它所依赖的类放在它自己的JAR中。在多个程序中重用JAR。

如果您使用Eclipse,可以通过创建一个新的Java项目(我们称之为项目OM--来自对象模型)并将Foo和FooManager类放在那里来实现。然后在每个项目中要重用对象,在项目的Build Properties中将OM项目添加到类路径和exports选项卡中。而已。

相关问题