gpt4 book ai didi

java - 在java中保存一个对象数组供以后在另一个程序中使用

转载 作者:行者123 更新时间:2023-11-29 05:56:27 28 4
gpt4 key购买 nike

好的,所以我的问题是我有很多在 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;
}

关于java - 在java中保存一个对象数组供以后在另一个程序中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11924843/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com