在这种情况下甚至无法找到问题本身。当程序从objects.dat读取时,输出只是数组中最后一个对象的变量。 程序输出截图。 代码我梳理了好几遍,都找不到问题所在。据我所知,一切都很顺利,直到它尝试将对象序列化和写入/读取到“objects.dat”。如果有人能给我一个关于问题是什么或如何解决它的提示,我将不胜感激。我认为问题可能出在 readFile 或 writeFile 方法中,但我不能确定。
目标是创建一个对象数组,对其进行序列化,将其写入文件,然后读取该文件。
public class Test implements Serializable{
public static void main(String[] args) throws InvalidTestScore, ClassNotFoundException, IOException {
Scanner keyboard = new Scanner(System.in);
int userInput;
final int ARRAYLENGTH;
//get info for ARRAYLENGTH and make a TestScore array.
System.out.println("How many test scores are you finding the average of? (ex. 6 tests): ");
ARRAYLENGTH = keyboard.nextInt();
TestScores[] scoreArray = new TestScores[ARRAYLENGTH];
//populate scoreArray with TestScore objects.
for (int counter = 0; counter < scoreArray.length; counter++)
{
System.out.println("Enter the score of test " + (counter + 1) + ": ");
userInput = keyboard.nextInt();
scoreArray[counter] = new TestScores(counter, userInput);
}
System.out.println("Now writing the object to 'objects.dat'...");
TestScores.writeFile(scoreArray);
System.out.println("Now reading the object from 'objects.dat'...");
TestScores.readFile(ARRAYLENGTH);
}
package scoresPackage;
import java.io.*;
public class TestScores implements Serializable {
static TestScores[] scoreArray, scoreRead;
static int score, name;
TestScores (int test, int num) throws InvalidTestScore
{
name = test;
score = num;
if (num >= 100 || num <= 0)
{
throw new InvalidTestScore();
}
}
public static void writeFile(TestScores[] test) throws IOException
{
FileOutputStream outStream = new FileOutputStream("objects.dat");
try (ObjectOutputStream objectOut = new ObjectOutputStream(outStream)) {
for (int counter = 0; counter < test.length; counter++)
{
objectOut.writeObject(test[counter]);
objectOut.reset();
}
}
System.out.println("Writing success.");
}
public static void readFile(int ALENGTH) throws IOException, ClassNotFoundException
{
FileInputStream inStream = new FileInputStream("objects.dat");
try (ObjectInputStream objectIn = new ObjectInputStream(inStream)) {
scoreRead = new TestScores[ALENGTH];
for (int counter = 0; counter < ALENGTH; counter++)
{
scoreRead[counter] = (TestScores) objectIn.readObject();
System.out.println("Test " + name + " Score: " + score);
}
}
System.out.println("Reading success.");
}