Hi All,

I've a little problem with writing and saving to a file
I'm close but I can't seem to grasp what i'm doing wrong here.

Trying to save student object(s) to allstudents.txt
This is my loadStudent method;

public student[] loadStudent() throws IOException, ClassNotFoundException
	//loads the accounts and returns them
	{
		ObjectInputStream fileInput = new ObjectInputStream(new FileInputStream("allstudents.txt"));
		student[] returnStudent = new student[MAX_STUDENTS];
		try
		{
			for (int i = 0; i < MAX_STUDENTS; i ++)
			{
				returnStudent[i] = (student)fileInput.readObject();
                System.out.println(returnStudent[i]);
			}
		}
		catch(EOFException e)
		{
			fileInput.close();
			return returnStudent;
		}
		return returnStudent;
	}

My save student is as follows

public void saveStudents(student[] saveStudents) throws IOException
	//saves the accounts to file
	{
            ObjectOutputStream fileOutput = new ObjectOutputStream(new FileOutputStream("allstudents.txt",true));	//the thing to save
            arrayStudent = saveStudents;
            for (int i = 0; i < arrayStudent.length; i ++)
            {
                fileOutput.writeObject(arrayStudent[i]);
                System.out.println(arrayStudent[i]);
            }
	}

What I don't get is the file allstudents.txt is growing each time I save the program
but next time I load nothing loads into memory, so there is error with my logic somewhere


Those methods are within a class "io"

My main class loads them as thus

io memory = new io();
memory.loadStudent();

Any assistance would be gratefully received !

Oh and my saveStudents() in my main is

private void saveStudents() throws IOException
	//saves the accounts into a file
	{
		memory.saveStudents(unistudent);
	}

some observations:

saveStudent 4: the "true" in the FOS specifies append mode, so that's why the file keeps growing.
saveStudent 5: what's arrayStudent and why do you use it?

Exception (non) handling. You seem determined to ignore IOExceptions. This is always a mistake. Catch them, and printStackTrace() the exception so you know what is, or isn't, happening.

You read/write an array one element at ta time. Why not just read/write the whole array as a single object?

It should append, as the student database grows, so that is good.

Array student is supposed to create a particular student and then
send it back to an array in my main

private student[] unistudent = new student[MAX_STUDENTS];

That's my student array

The idea of writing one element at a time was to
"Add new student" and then save progressively after each student in case of program failure

My io file has

private student[] arrayStudent;
	private static final int MAX_STUDENTS = 10;

I can't directly access the private student array in my main method
so I thought I could use arrayStudent to circumvent this, but I don't seem to have
it licked as to it's real purpose.

My code flow I wanted to be something like

addstudent (in main)
take input for the variables
then call saveStudent() in main
which calls saveStudents() passing in unistudent (the name of the Student array)
which I hoped would save to a text.

OK, that clarifies it a lot.

Your loadStudent method looks like it going the right way - creating, loading, and returning an array of Students from the file.
But look at how you call it

io memory = new io();
    memory.loadStudent();

what do you do with the array it returns??? Right now you ignore it, and it gets lost. Maybe you should assign the returned array to something...?

Thank you James, you make an excellent point,
Since it loads one student at a time to populate the list
Would a for loop assigning unistudent to memory.loadStudent()
work? Or am I looking at that the wrong way?

I wrote a new method, still not having much luck but I think I am closer to what I need to do
For clarification here are 2 of the classes that i'm working with at the moment


gradCheck (main class)

import java.util.*;
import java.lang.Integer;
import java.io.*;

public class gradCheck


{
    private static final int MAX_STUDENTS = 10;
    private student[] unistudent = new student[MAX_STUDENTS];
    private int currentAccount = 0;
    private student selectedStudent;
    
	private static Scanner input = new Scanner(System.in);
    private program[] prog = new program[1];
    private course[] courses = new course[1];
    private enrolment[] enrol = new enrolment[1];
    io memory = new io();

        
	public static void main(String[] args)
	{
        gradCheck graduation = new gradCheck();
        graduation.loadAllData();
        graduation.displayMenu();
        
    }

    private void loadAllData()
    {
        try
        {
            prog[0] = new program();
            prog[0].loadProgram();
            courses[0] = new course();
            courses[0].loadCourse();
            enrol[0] = new enrolment();
            loadStudent();
        
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        
        
    }
    
    
	public void displayMenu()
	{	
		System.out.println("-------------------------------");
		System.out.println("Welcome to the Graduation Checker");
		System.out.println("");
		System.out.println("");
		System.out.println("1 - Graduation Checker");
		System.out.println("2 - Create Student");
		System.out.println("3 - Update Results");
		System.out.println("4 - Modify The Program");
        System.out.println("5 - Exit Program");
		System.out.println("");
		System.out.println("");
		System.out.print("Please enter your choice  >>  ");
        getChoice();
	}
    
    
	
	public void getChoice()
	{
		int choice = input.nextInt();
        processChoice(choice);
        
	}
    
	
	public void processChoice(int choice_)
    {	        		
			switch (choice_)
			{
				case 1:
				{
					break;
				}
				case 2:
				{
					addStudent();
                    loadAllData();
					break;
				}
				case 3:
				{
					courses[0].printCourses();
					break;
				}
				case 4:
				{
					prog[0].modifyProgram();
					break;
				}
                case 5:
				{
                    try
                    {
                        saveStudents();
                    }
                    catch (Exception e)
                    {
                        System.out.println("Error saving file");
                    }
					System.exit(0);
					break;
				}
				default:
				{
					System.out.println("Invalid please try again");
				}
			}
            try
            {
                displayMenu();
            }
            catch (Exception e)
            {
                System.err.println("Error: " + e.getMessage());
            }
		}
    
    public void addStudent()
	//creates the account if error checking allows it
	//otherwise returns the message number and displays is accordingly
	{
		System.out.print("Enter Student's First Name  >>  ");
		String tempFirstName = input.next();	//a temp name
		
		System.out.print("Enter Student's Last Name  >>  ");
		String tempLastName = input.next();	//a temp address
		
        System.out.print("Enter Student's ID Number  >>  ");
        String tempStudentID = input.next();
		

		int msgCheck = createAccount(tempFirstName, tempLastName, tempStudentID);	
		//int msgCheck = 0;
		//show the message
		switch (msgCheck)
		{
			case 0:
				System.out.println("Student successfully added!");
				break;
			case 1:
				System.out.println("No Name was entered");
				break;
			case 2:
				System.out.println("No Last Name was entered");
				break;
			case 3:
				System.out.println("No First or Last was entered");
				break;
			case 4:
				System.out.println("A student with that name already exists");
				break;
			case 5:
				System.out.println("No more accounts can be added");
				break;
			default:
				System.out.println("There was an unknown error.");	//any other unknown error that may occur
		}
        
	}
    
	public int createAccount(String firstName_, String lastName_, String studentID_)
	
	//Returns a number depending on what happens
	//0 - successfully created
	//1 - blank name
	//2 - blank address
	//3 - both fields blank
	//4 - duplicate account
	//5 - array full
	{
		if (currentAccount < MAX_STUDENTS)
		{
			int temp = checkDetails(firstName_, lastName_, studentID_);	//if any fields are blank
			if (temp == 0)
			{
				//account can be created
				unistudent[currentAccount] =  new student(firstName_, lastName_);
				currentAccount ++;
                try
                {
                    saveStudents();
                }
                catch (Exception e)
                {
                }
			}
			return temp;	//returns temporary value
		}
		else
		{
			return 5;	//returns error number 5
		}
	}
	
	public student getSelectedStudent()
	//returns the selected account
	{
		return selectedStudent;
	}
	
	public int checkDetails(String firstName_, String lastName_, String studentID)
	//checks if firstName_ or lastfirstName_ is blank
	//0 - no blank fields
	//1 - blank first name
	//2 - blank last name 
	//3 - both fields blank
	//4 - duplicate account
	{
		student tempStudent = new student(firstName_, lastName_);	//creates a temporary account to check
		if ((firstName_ == null) && (lastName_ == null))
		{
			return 3;	//both empty
		}
		else
		{
			if (firstName_ == null)
			{
				return 1;	//blank first name
			}
			else
			{
				if (lastName_ == null)
				{
					return 2;	//blank last name
				}
				else
				{
					//it goes through all accounts and checks them
					for (int i = 0; i < currentAccount; i ++)
					{
						if (unistudent[i].equalsTo(tempStudent))
						{
							return 4;	//duplicate acocunt
						}
					}
					return 0;	//account can be created
				}
			}
		}
	}
    
    
    public void saveStudents() throws IOException
	//saves the accounts into a file
	{
		memory.saveStudents(unistudent);
	}
	
    public void loadStudent() throws IOException, ClassNotFoundException
	//loads the accounts from a file
	{
		unistudent = memory.loadStudent();
		int loader = MAX_STUDENTS;	//makes the loop happen the right amount of times
		for (int i = 0; i < loader ; i ++)
		{
			if (unistudent[i] != null)
			{
				System.out.println(unistudent[i].getFirstName() + unistudent[i].getLastName() + unistudent[i].getStudentID());
				currentAccount++;
			}
			else
			{
				loader = -1;
			}
		}
	}
}

and IO

import java.io.*;
import java.util.*;

public class io
{
	private student[] arrayStudent;
	private static final int MAX_STUDENTS = 10;
	
	public void saveStudents(student[] saveStudents) throws IOException
	//saves the accounts to file
	{
            ObjectOutputStream fileOutput = new ObjectOutputStream(new FileOutputStream("allstudents.txt",true));	//the thing to save
            arrayStudent = saveStudents;
            for (int i = 0; i < arrayStudent.length; i ++)
            {
                fileOutput.writeObject(arrayStudent[i]);
            }
	}
	
	public student[] loadStudent() throws IOException, ClassNotFoundException
	//loads the accounts and returns them
	{
		ObjectInputStream fileInput = new ObjectInputStream(new FileInputStream("allstudents.txt"));
		student[] returnStudent = new student[MAX_STUDENTS];
		try
		{
			for (int i = 0; i < MAX_STUDENTS; i ++)
			{
				returnStudent[i] = (student)fileInput.readObject();
			}
		}
		catch(Exception e)
		{
			fileInput.close();
			return returnStudent;
		}
		return returnStudent;
	}
}
Member Avatar for hfx642

1. It looks as if you are trying to handle a text file using binary routines.
Rename your file with something other than a *.txt file extention.
2. Since you are using binary file handling routines... you're missing the "get" method from your "student" class.

Thank you , wow I was using a text based save (I still am for my courses/program objects) and I completely forgot to change the filename, It works perfectly now.
Thank you so much hfx argh!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.