Why can I serialize attributes but not the object itself? [duplicate] - java

This question already has answers here:
Why does writeObject throw java.io.NotSerializableException and how do I fix it?
(4 answers)
Closed 6 years ago.
I am working on a little quiz tool and face problems when I want to persist my objects (questions). This is my save method within the class Question, which imports "java.io.*":
public static boolean saveQuestion(String file, Question q){
try{
FileOutputStream saveFile=new FileOutputStream(file);
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(q);
save.close();
return true;
}
catch(Exception exc){
exc.printStackTrace();
return false;
}
}
This is how I call the method from another class:
Question q = new Question();
Question.saveQuestion("question.sav",q);
When I try to run it, it throws a "java.io.NotSerializableException" at the save.writeObject(q);
When I change my code in order to just store an attribute of the object it works fine. What can be the problem?

To serialize objects, your classes needs implements Serializable.

Related

Adding elements to an empty ArrayList<T> [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am adding objects to an ArrayList that is initialized as null inside a for each loop, but SonarLint is giving me a "NullPointerException" could be thrown when I try to add each object. Why is this error being pointed out?
public List<SatelliteData> getData()
{
SatelliteData satellite;
ArrayList<SatelliteData> satelliteList = null;
try(FileInputStream file = new FileInputStream(satelliteOutputFile))
{
TLEParser parsedFile = new TLEParser();
List<TLE> tleList = parsedFile.readFile(file);
for (TLE tle : tleList)
{
satellite = new SatelliteData(tle);
satellite.collectSatelliteData();
satelliteList.add(satellite); //A "NullPointerException" could be thrown; "satelliteList" is nullable here
}
}
catch (IOException ex)
{
LOGGER.error("IO Exception: " + ex);
notifyTheObservers("IO Exception: " + ex);
}
return satelliteList;
}
You shouldn't call member methods on variables that have been initialized to nothing/null.
In this case you have
ArrayList<SatelliteData> satelliteList = null;
This variable does not have any memory allocated to it.
At this point your computer knows : Okay there exists something
called satelliteData but it actually doesn't know where it is?
Calling add() method on it, is likely to throw a NullPointerException because this variable is a reference that is pointing to null/nothing.
To overcome this, You need to initialize the variable like this :
ArrayList<SatelliteData> satelliteList = new ArrayList<SatelliteData>();
At this point your computer created that satteliteData and knows
exactly where it exists hence it can happily operate upon it.
This will allocate some memory to this variable and now it has its own methods you can call.

Java - metode inside a metode syntax issues [duplicate]

This question already has answers here:
Does Java support inner / local / sub methods?
(5 answers)
Closed 5 years ago.
Really don't know what it's called so I'm having a hard time searching for the answer.
Anyhow, I want to make a metode with metode inside (if that's even possible?).
public void log() {
public makeLogElement() {
//making a logelement to write inn
}
public write(String text) {
logelement.setText(logelement.getText() + text);
}
}
log myLog = new log();
myLog.makeLogElement();
myLog.write("This'll be written in the log");
What is the right syntax for making something like this?
It's not possible. But you can create a class inside a method.

Using iterator inside a method with ArrayList [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Can someone explain to me if what this method mean?
clientOutputStreams = new ArrayList();
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch(Exception ex){ex.printStackTrace();}
}//end while
}//end method
Any help would be appreciated.
It seems to be implementing an Observer pattern where subscribers are the output streams targets.
That is, you have a list of output streams where the message is going to be published whenever someone calls to tellEveryone method. Having the output streams references stored in a list allows to easily add "listeners", in this case, output channels without changing your code.
This is your code commented:
clientOutputStreams = new ArrayList(); //Subscribers list
...
...
public void tellEveryone(String message) { //Publish your message writing it in each single outPutStream
Iterator it = clientOutputStreams.iterator(); //Get an iterator to traverse the subscriber list
while(it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message); //Print the message.
writer.flush();
} catch(Exception ex){ex.printStackTrace();} //Catch any posssible exception, (what happens if one stream is closed?)
}//end while
}//end method
An example of use could be a log for which you want the messages to be sent through a socket connection as well as to be stored in a file. To perform that task you just have to add the socket's PrintWriter object and your file's PrintWriter to clientOutputStream once.
Then, whenever a message is to be logged you just have to call to tellEveryone and it will be stored in the file and sent to the connection receiver.
This method seems to output the "clientOutputStreams" to the "message", and turned the ASCII code into the default character set. The iterator, in my view, it looks like a poniter, points to the element of the array.

Constructor for importing file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
If I wanted to build a constructor for a class to import a file, which I have passed in a String nameOfFile, how can I initialize the object's state, then open the document file, and process each line of the document? References and clear explanation would be appreciated. I'm just beginning to learn java.
To clear up my question, how can you build an object for a document file you have imported? What I'm doing right now is that I have wrote a class but i'm struggling with building an object for a SPECIFIC file. What I have thus far is
public class theImport
{
theImport(String nameOfFile)
{
(Here is where I want to achieve all the listing I have above.)
}
.
.
.
}
I believe you would do this in a two-step process.
Step one: The actual constructor.
private String nOF;
public ClassName(String nameOfFile) {
nOF = nameOfFile;
}
Step two: Evaluation of the file. Since this can fail for a variety of reasons (for example the file not existing, it shouldn't go to the constructor (you can't catch these errors from a return type you aren't having in the constructor)
public boolean Evaluate() {
//Evaluate your file and return false if it fails for whatever reason.
}
My Java isn't the best at the moment, but this should tip you in the right direction.
Propably you mean something like this:
public class theImport
{
theImport(String nameOfFile)
{
try {
FileReader input = new FileReader(nameOfFile);
BufferedReader bufRead = new BufferedReader(input);
String line;
line = bufRead.readLine();
//this will loop thought the lines of the file
while (line != null){
line = bufRead.readLine();
//do whatever you want with the line
}
bufRead.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}

Appending Objects to a .txt file [duplicate]

This question already has an answer here:
StreamCorruptedException: invalid type code: AC
(1 answer)
Closed 5 years ago.
I was trying out a program that was given in the exercise at the end of the chapter 'Serialization'.
The program requires me to declare a class Person which encapsulates only two data members of type Name and Address , which are also classes.
Then I have to take a series of names and addresses from the keyboard , create objects and write them to the file.
However , if the FILE ALREADY EXISTS then the objects must be APPENDED to the existing file.
My program runs perfectly for the first time but for the second time , when I try to read back the appended records , I get an Exception
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at Trial.main(Trial.java:66)
I did my bit of research on this and found that the StreamHeader can be written ONLY ONCE and appending corrupts it.
What is the way around it ???
The Object Writing Code is:
try(ObjectOutputStream stream = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(filePath,WRITE,CREATE,APPEND)))) {
for(int i = 0;i<name.length;i++) {
Person aPerson = new Person(name[i],address[i]);
System.out.println(aPerson);
stream.writeObject(aPerson);
stream.reset();
aPerson = null;
}
System.out.println("Writing Complete");
Yes, I've had this problem myself before... it is not possible, unfortunately.
What you could do is to place your objects into a List and persist the full list at a time. As the list is an object it can persisted just as easily. I know this is terrible as this require the entire contents to be read into memory, but it is the only way as far as I know.
The other option (which I recommend) is that you use something like JSon to commit your data. GSon works quite well for this purpose. You can then simply marshall and unmarshall your objects which can be committed to a text file. It's very easy to do as a single line of code is required to go either way (object to JSon-string and vice versa).
This works. So debug your program and see why it doesn't. Probably don't call reset()
public class ClassTest {
public static void main(String a[]) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/temp/foo.txt"));
oos.writeObject(new Test("foo", "bar"));
oos.writeObject(new Test("baz", "brr"));
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:/temp/foo.txt"));
System.out.println(ois.readObject());
System.out.println(ois.readObject());
ois.close();
}
}
class Test implements Serializable {
private String fld1;
private String fld2;
public Test(String v1, String v2) {
this.fld1 = v1;
this.fld2 = v2;
}
#Override
public String toString() {
return "Test [fld1=" + fld1 + ", fld2=" + fld2 + "]";
}
}

Categories