gpt4 book ai didi

java - 打印对象到文件txt

转载 作者:行者123 更新时间:2023-12-02 06:45:57 24 4
gpt4 key购买 nike

我正在尝试将对象打印到文件中。然后我想将它们导入回我的程序中。ObjectOutputStream 不起作用,我错过了什么? (尝试一下,发现这里不可见,但他们正在做他们的工作)

Map< Account, Customer> customerInfo = new HashMap< Account, Customer>();

File bankFile = new File("Bank.txt");
FileOutputStream fOut = new FileOutputStream( bankFile);
ObjectOutputStream objOut = new ObjectOutputStream(fOut);

for(Map.Entry<Account, Customer> e : bank.customerInfo.entrySet())
{
objOut.writeObject(e.getValue());
objOut.writeObject(e.getKey());
}

objOut.flush();
objOut.close();
fOut.close();

我的问题是 ObjectOutputStream 无法正常工作,它打印一些奇怪的代码。我已经使用其他方法打印到文件,它们工作得很好。

我尝试打印到不同的文件扩展名,

我尝试更改文件和 eclipse 的编码。

我尝试了不同的方法来使用 ObjectOutputStream 从 map 获取信息。 ObjectOutputStream 打印我没有想到的奇怪字符是否有原因?整个文件几乎无法读取。谢谢!

诗。一些奇怪的打印,不知道是否有帮助。

ØísrCustomerDìUðkJPersonalIdNumLnametLjava/lang/String;xpthellosrSavingAccountUÞÀÀ;>ZfreeWithdrawDwithdrawalInterestRateLaccountTypeq~xrAccount é=UáÐIaccountNumberDbalanceDinterestRateLaccountTypeq~L transListtLjava/util/List;xpé?záG®{tsrjava.util.ArrayListxÒÇaIsizepwx?záG®{t储蓄账户q~sr信用账户Ý*5&VcLaccountTypeq~xq~ê?záG®{q~sq~ wxt信用账户

最佳答案

这真的很简单。首先,创建一个实现 Serialized 的类。 Serialized 是一个标记接口(interface),因此您不需要为它实现任何方法:

public class Shoe implements Serializable  { ... }

<小时/> 注意:如果 Shoe 中有其他类,例如 HeelBuckle >,这些类还需要实现 Serialized 接口(interface)。

<小时/>

下一步是使用 ObjectOutputStream 将其写入文件。

FileOutputStream out = new FileOutputStream("myfile.txt");
// Create the stream to the file you want to write too.
ObjectOutputStream objOut = new ObjectOutputStream(out);
// Use the FileOutputStream as the constructor argument for your object.

objOut.writeObject(new Shoe("Prada"));
// Write your object to the output stream.
objOut.close();
// MAKE SURE YOU CLOSE to avoid memory leaks, and make sure it actually writes.

给你了。序列化的对象写入txt文件。现在来阅读它,这只是使用 ObjectInputStream 的一个例子。

ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("myfile.txt");
Object obj = objIn.readObject();
if(obj instanceof Shoe)
{
Shoe shoe = (Shoe)obj;
}

你已经有了一个可以使用的对象。

关于java - 打印对象到文件txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18633622/

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