在java中保存一个对象数组,以便以后在另一个程序中使用 [英] Saving an array of objects in java for later use in another program
本文介绍了在java中保存一个对象数组,以便以后在另一个程序中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试
{
FileOutputStream fileOut = new FileOutputStream(card.ser); //在输出流中创建一个卡串行文件
ObjectOutputStream out = new ObjectOutputStream(fileOut); //将一个对象路由到输出流中。
out.writeObject(array); //我们指定我们的数组被路由
out.close(); //关闭数据路径
fileOut.close(); //关闭数据路径
} catch(IOException i)//异常内容
{
i.printStackTrace();
$ / code>
来反序列化它:
try //如果这不起作用会抛出异常
{
FileInputStream fileIn = new FileInputStream(name +.ser); //读取串行文件。
ObjectInputStream in = new ObjectInputStream(fileIn); //输入读取的文件。
object =(Object)in.readObject(); //将其分配给已经实例化的对象文件。
in.close(); //关闭输入流。
fileIn.close(); //关闭文件数据流。
catch(IOException i)//异常东西
{
i.printStackTrace();
return;
catch(ClassNotFoundException c)//更多的异常东西
{
System.out.println(Error);
c.printStackTrace();
return;
}
Okay, so my issue is that i have alot of programs that i am using in java that use the exact same array of objects but i dont want to keep recreating this array every time that i write a new program. Is there a way to save an array of objects for use in other java programs. if so how?
解决方案
If you are a beginner you should serialize the array of objects into a file. The convention is to name your serialized file 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();
}
to deserialze it use this:
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;
}
这篇关于在java中保存一个对象数组,以便以后在另一个程序中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文