在java中保存一组对象,以便以后在另一个程序中使用

好吧,所以我的问题是我有很多程序,我在java中使用完全相同的对象数组但我不想每次写一个新程序时继续重新创建这个数组。 有没有办法保存一个对象数组,以便在其他java程序中使用。 如果是这样的话?

如果您是初学者,则应将对象数组序列化为文件。 惯例是命名序列化文件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; } 

要序列化对象,请创建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 ); 

参考

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

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

如果你使用Eclipse,你可以通过创建一个新的Java项目(让我们称之为项目OM – 来自Object Model)并将Foo和FooManager类放在那里来实现。 然后在每个要重用对象的项目中,在项目的“构建属性”中将OM项目添加到类路径和导出选项卡。 而已。