5

I'm trying to save an object, I googled the HowTo and got a tutorial on this issue. However since I never worked before with this I'm experiencing problems I can't resolve.

So I have a huge class Course (contains all sort of things, variables, collectors...) which I'm trying to save in a file.

import java.io.Serializable;
class Person implements Serializable {
... }

Now, I send an object to a class Save.java and try to save it :

class Save {

    protected void saveCourse (Course course) {

        FileOutputStream courseFile = new FileOutputStream("course.data");

        ObjectOutputStream courseObj = new ObjectOutputStream(courseFile);

        courseObj.writeObject(course);
    }
}

When I try to compile it FileOutputStream and ObjectOutputStream "cannot be resolved to a type". Aren't they suppose to be predefined. How can I fix this

Tutorial where I got this can be found here.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
vedran
  • 2,167
  • 9
  • 29
  • 47

2 Answers2

15

You need to import FileOutputStream and ObjectOutputStream.

Since they are both in the java.io package, that means that you'll need to add this to the top of your file (under the package declaration, if you have one):

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

Also be careful about choosing your Java tutorials: there are lots of bad tutorials out there. The official Java tutorials from Oracle are pretty good (at least they are much better than most other stuff out there) and should cover everything you need for quite some time.

For example there's a nice tutorial about using ObjectOutputStream and related classes.

More details about packages and importing can be found in this tutorial.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • I did and it worked. At least one part of it did. Now I'm getting "Unhandled exception type FileNotFoundException" error. How could I throw an exception to handle such error in my example? – vedran Nov 02 '11 at 12:07
  • 1
    Surprise! There's [a tutorial on exceptions](http://download.oracle.com/javase/tutorial/essential/exceptions/)! – Joachim Sauer Nov 02 '11 at 12:08
  • Ok, so I managed to work everything out. It works, however, I'm getting a warning in eclipse "The serializable class Course does not declare a static final serialVersionUID field of type long" when declaring Course class. I've searched for this but couldn't fin a clear answer. Would you happen know what does this mean? – vedran Nov 02 '11 at 12:28
  • 1
    Googling for `serialVersionUID` shows this as one of the first hits: http://stackoverflow.com/questions/285793/why-should-i-bother-about-serialversionuid – Joachim Sauer Nov 02 '11 at 12:31
0

To handle exceptions, normally put your code in a try-catch block

George Otieno
  • 536
  • 4
  • 10