为什么 ObjectOutputStream 将符号写入文件而不是我的输入?
Why does ObjectOutputStream write symbols to a file instead of my input?
我正在尝试将名为 Clients
的 ArrayList
写入文件。它有效,但不幸的是它只是将符号写入文件而不是我的实际输入。
下面是我的代码:
public void SaveToFile() {
try
{
FileOutputStream fos = new FileOutputStream("CustomerLists.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(Clients);
oos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
如何让它发挥作用?
您所做的是 将 Java 对象序列化 到具有 ObjectOutputStream
的文件。这意味着,Java 将你的对象 Clients
转换为一个特定的表示,它涵盖了你的对象所具有的所有状态,例如成员变量。这种表示并不意味着人类可读,它是一种 二进制格式 ,比 类 和 Java 环境更有效,更适合文本格式。查看 here 了解更多信息。
你可以做的是使用 FileWriter
, BufferedWriter
or PrintWriter
, which have multiple write[...](...)
methods to write text to a file. In this case, you have to write each variable for its own as String
, etc., not the whole class. Here 你可以找到一个例子。
对整个对象执行与 ObjectOutputStream
相同但以完全可定制的方式和人类可读的形式的另一种选择是使用 Java Architecture for XML Binding (JAXB),但这需要一些阅读。 JSON 和其他格式还有其他对象序列化库。
Why is it when I run this java program it creates the text file but it prints out symbols instead of my input?
因为它不是文本文件。它是序列化数据,根据 Java 序列化协议编写,因为您使用的是 ObjectOutputStream.writeObject()
.
这也意味着 CustomerLists.txt
不是该文件的合适名称。
如果需要文本,请使用 PrintWriter
或 BufferedWriter
。
我正在尝试将名为 Clients
的 ArrayList
写入文件。它有效,但不幸的是它只是将符号写入文件而不是我的实际输入。
下面是我的代码:
public void SaveToFile() {
try
{
FileOutputStream fos = new FileOutputStream("CustomerLists.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(Clients);
oos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
如何让它发挥作用?
您所做的是 将 Java 对象序列化 到具有 ObjectOutputStream
的文件。这意味着,Java 将你的对象 Clients
转换为一个特定的表示,它涵盖了你的对象所具有的所有状态,例如成员变量。这种表示并不意味着人类可读,它是一种 二进制格式 ,比 类 和 Java 环境更有效,更适合文本格式。查看 here 了解更多信息。
你可以做的是使用 FileWriter
, BufferedWriter
or PrintWriter
, which have multiple write[...](...)
methods to write text to a file. In this case, you have to write each variable for its own as String
, etc., not the whole class. Here 你可以找到一个例子。
对整个对象执行与 ObjectOutputStream
相同但以完全可定制的方式和人类可读的形式的另一种选择是使用 Java Architecture for XML Binding (JAXB),但这需要一些阅读。 JSON 和其他格式还有其他对象序列化库。
Why is it when I run this java program it creates the text file but it prints out symbols instead of my input?
因为它不是文本文件。它是序列化数据,根据 Java 序列化协议编写,因为您使用的是 ObjectOutputStream.writeObject()
.
这也意味着 CustomerLists.txt
不是该文件的合适名称。
如果需要文本,请使用 PrintWriter
或 BufferedWriter
。