import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class StudentWriteApp extends Frame implements ActionListener
{
    //Declare stream objects
    FileOutputStream outputStudent; //Stream to create file
    ObjectOutputStream objSaveStudent; //Stream to save an object

    //Declare components
    TextField txtStudentName = new TextField(20);
    TextField txtAddress = new TextField(20);
    TextField txtResults = new TextField(25);
    Button btnSave = new Button("Save");
    Button btnBack = new Button("Back");

    public static void main(String args[])
    {
        //Declare an instance of this application
        StudentWriteApp thisApp = new StudentWriteApp();
        thisApp.openStream();
        thisApp.createInterface();
    }

    public void openStream()
    {
        try
        {
            //Create file and object output streams
            outputStudent = new FileOutputStream("Student.txt");
            objSaveStudent = new ObjectOutputStream(outputStudent);
        }
        catch(Exception error)
        {
            System.err.println("Error opening file");
        }
    }

    public void closeStream()
    {
        try
        {
            objSaveStudent.close(); //Close the object output stream
            outputStudent.close();  //Close the file output stream
        }
        catch (IOException error)
        {
            System.err.println("Error closing file");
        }
    }

    public void createInterface()
    {
        //Set up user interface for this frame
        setTitle("Save Student Objects");
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent event)
            {
                closeStream();
                System.exit(0);
            }
        });
        setLayout(new FlowLayout());
        add(new Label("Student Name "));
        add(txtStudentName);
        txtStudentName.requestFocus();
        add(new Label("Address "));
        add(txtAddress);
        add(new Label("Results "));
        add(txtResults);
        add(btnSave);
        add(btnBack);
        btnSave.addActionListener(this);
        btnBack.addActionListener(this);
        txtStudentName.addActionListener(this);
        txtAddress.addActionListener(this);
        txtResults.addActionListener(this);
        setSize(300, 150);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {

         if (e.getSource() == btnBack) 
            { 
            this.setVisible(false);
            FrontPage pass = new FrontPage();
            pass.setVisible(true);
            } 

        //Save Student object
        try
        {
            Student empCurrent = new Student(txtStudentName.getText(),
                                    txtAddress.getText(),
                                    txtResults.getText());
            objSaveStudent.writeObject(empCurrent);
            //objSaveStudent.flush();
            txtStudentName.setText("");
            txtAddress.setText("");
            txtResults.setText("");
            txtStudentName.requestFocus();
        }
        catch(Exception error)
        {
            System.err.println("Error writing to file");
        }
    }
}

Recommended Answers

All 6 Replies

Next time use the button (code) when posting code and put it inside the tags.

Question: Have you implemented the java.io.Serializable interface?

Ok. No I haven't, is there anyway to create a new file each time you try write?

Ok. No I haven't, is there anyway to create a new file each time you try write?

In order to be able to write using ObjectOutputStream you need this at the object you are trying to write: implements java.io.Serializable If that object has other objects as attributes those object also need to implement the same. Some java object also implement that interface such as the java.lang.String object. Which is why you can write your Student object. For primitive types (int) you are ok.

If you want a different file then with button click, you will need new FileOutputStream and ObjectOutputStream objects with file you want. You will need to close them as well.:

FileOutputStream fos = new ....
ObjectOutputStream objSaveStudent = new ....
Student empCurrent = new Student(txtStudentName.getText(),
txtAddress.getText(),
txtResults.getText());
objSaveStudent.writeObject(empCurrent);

// close them

I think that if that you can save multiple objects in one file. But when you read you will have to call the readObject method multiple times as well. If you don't know how many just keep calling it until you get an Exception. Then catch it without doing anything and continue with the code.

thanks, appreciate it

I have tested the code and for the first version, the students are saved successfully. The problem occurred when I closed the application and run it again. The old students where replaced by the new entries.
I tried creating the FileOutputStream like this, with no luck:

outputStudent = new FileOutputStream("Student.txt", true); // check the API

So I would suggest when you start the app, to read all the written students and to rewrite them before adding new ones. It is better for this case not to save Student objects but one Vector object:

private Vector<Student> students = new Vector<Student>();

public void actionPerformed(ActionEvent e)
{
Student empCurrent = new Student(txtStudentName.getText(), ... ,...);

students.add(empCurrent);

txtStudentName.setText("");
txtAddress.setText("");
txtResults.setText("");
txtStudentName.requestFocus();
}


public void windowClosing(WindowEvent event)
{
objSaveStudent.writeObject(students);
closeStream();
System.exit(0);
}

PS: At the empCurrent variable, what does the 'emp' stands for?

it was just a line of code from an old project and i never changed it.
its still creating a new file everytime, do you think bufferwriter and reader could work

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.