gpt4 book ai didi

Java编程: Storing Objects and Arrays into a file

转载 作者:行者123 更新时间:2023-12-01 06:57:22 25 4
gpt4 key购买 nike

*我的作业是编写一个程序,存储五个 int 值 1、2、3、4 和 5 的数组、当前时间的 Date 对象和 double 值 5.5。到名为 Exercies19_2.txt 的文件中。接下来,我将在程序中编写一个方法,打开Exercises19_2.txt,读取数据并显示到命令窗口。当我运行我的程序时,我不断收到以下消息:

Exception in thread "main" java.io.OptionalDataException at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readObject(Unknown Source) at WriteArray.main(WriteArray.java:29).

你能帮我找出我做错了什么吗???这是我写的:

    import java.io.*;

public class WriteArray {

public static void main(String[] args)throws ClassNotFoundException,IOException {
int[] numbers = {1, 2, 3, 4, 5};

//Create an output stream for file
ObjectOutputStream output = new ObjectOutputStream
(new FileOutputStream("Exercises19_2.txt", true));

//Write to file
output.writeDouble(5.5);
output.writeObject(numbers);
output.writeObject(new java.util.Date());
output.writeUTF("Exercises19_2.txt");

//Close the stream
output.close();

//Create an input stream for file
ObjectInputStream input = new ObjectInputStream
(new FileInputStream("Exercises19_2.txt"));

int[]newNumbers = (int[])(input.readObject());
for (int i = 0; i < newNumbers.length; i++)
System.out.println("Integers: " + newNumbers[i] + " ");

String FileName= input.readUTF();
double Double = input.readDouble();
java.util.Date date = (java.util.Date)(input.readObject());
System.out.println("DateTime: " + date);


//Display the output

System.out.println("Double: " + " " + input.readDouble());
System.out.println("FileName: " + " " + input.readUTF());

//Close the stream
input.close();


}
}

最佳答案

当序列化和反序列化到 objectOutputStream 时,您必须按照写入对象的顺序读入对象。您写入文件的第一件事是带有 output.writeDouble(5.5); 的 double ,因此您需要先读回 double ,然后才能读取数字数组。

关于Java编程: Storing Objects and Arrays into a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8370424/

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