在java中保存对象数组以供以后在另一个程序中使用
好的,我的问题是,我在java中使用的很多程序都使用完全相同的对象数组,但我不想每次编写新程序时都重新创建这个数组。是否有一种方法可以保存对象数组以供其他java程序使用。如果是,如何序列化?要序列化对象,请创建ObjectOutputStream并调用writeObject在java中保存对象数组以供以后在另一个程序中使用,java,file,Java,File,好的,我的问题是,我在java中使用的很多程序都使用完全相同的对象数组,但我不想每次编写新程序时都重新创建这个数组。是否有一种方法可以保存对象数组以供其他java程序使用。如果是,如何序列化?要序列化对象,请创建ObjectOutputStream并调用writeObject // Write to disk with FileOutputStream FileOutputStream f_out = new FileOutputStream("myobject.data"); //
// 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 );
如果您是初学者,应该将对象数组序列化为文件。约定是将序列化文件命名为name-of-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();
}
要对其进行反序列化,请使用以下命令:
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;
}
可以序列化多种类型的对象。是的,数组也是一个对象(@参见数组类)。如果不考虑数组的限制,也可以使用一个容器类(例如LinkedList)。序列化的工作方式相同。编写一个类来管理此数组。将这个类以及它所依赖的类放在它自己的JAR中。跨多个程序重复使用JAR 如果您使用Eclipse,您可以通过创建一个新的Java项目(让我们称之为project OM-from Object Model)并将Foo和FooManager类放在那里来实现这一点。然后,在要重用对象的每个项目中,在项目的“生成属性”中将OM项目添加到类路径和“导出”选项卡中。就这样