0

It is clear that I can't write the Test object to the file Test.dat, my question is what exactly is the reason that it will not succeed?

import java.io.*;

public class Test {

    private int a = 10;
    private double b = 7.5;
    private String m = "valu";

    public static void main(String[] args) {
        Test t = new Test();

        ObjectOutputStream output = ObjectOutputStream(new FileOutputStream("Test.dat"));
        output.writeObject(t);
        output.close();
    }
}
2
  • what error your getting? Commented Feb 27, 2015 at 17:07
  • Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method ObjectOutputStream(FileOutputStream) is undefined for the type Test at hst17.Test.main(Test.java:15) Commented Feb 27, 2015 at 17:08

2 Answers 2

2

Apart from new key word, you forgot to implement Serializable

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Test implements Serializable{

    private int a = 10;
    private double b = 7.5;
    private String m = "valu";

    public static void main(String[] args) throws IOException {
        Test t = new Test();

        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("Test.dat"));
        output.writeObject(t);
        output.close();
    }

}
Sign up to request clarification or add additional context in comments.

Comments

1

Try

ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("Test.dat"));

You had missed the "new" so the compiler is looking for a static method rather than the constructor

2 Comments

great, thank you very much. It works when I add a FileNotFoundException, IOException and the new ObjectOutputStream.
Please accept an answer if someone has answered it correctly. In this case Ramesh put a bit more effort in so I won't be offended if you choose his ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.