Cannot even find the problem itself in this case. When the program reads from objects.dat, the output is only the variables of the last objects in the array. Program output screenshot. I have combed through the code several times and cannot find the problem. As far as I am aware everything is smooth up until it tries to serialize and write/read the objects to "objects.dat". If anybody could give me a hint as to what the problem is or how to go about fixing it, I'd greatly appreciate it. I think the problem might be in either the readFile or writeFile method but I cannot be sure.
The goal is to make an object array, serialize it, write it to a file, and then read the file.
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.");
}