java serialization working unexpectedly? - java

Hi If a class cannot implement serializable interface and if we try to serialize it, we should get a NotSerializableException. Here I am not getting it. The Cat class doesn't implement Serializable and I try to serialize it. Compiled and run fine why?
import java.io.*;
class Cat{}
class MyTest{
public static void main(String a[]){
Cat c = new Cat();
try{
FileOutputStream fos = new FileOutputStream("test.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(c);
oos.close();
fos.close();
}
catch(Exception e){e.getMessage();}
try{
FileInputStream fis = new FileInputStream("test.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (Cat)ois.readObject();
ois.close();
fis.close();
}
catch(Exception e){e.getMessage();}
}
}

It is throwing exceptions, you are just swallowing them with
catch(Exception e){e.getMessage();}
which just calls a method that returns a String, it doesn't log anything.
Use
e.printStackTrace();

Related

Modifying objects in binary file

Considering I have an object from a custom class and I write it to a .dat file using FileOutputStream and ObjectOutputStream . How will I modify a object present in the file? I can only read or write objects into a file..
I know that we can create a temporary file and then renaming the file accordingly, but isnt there any other way?
I do get outputs as expected , but isnt there any other method?
Yes you can do it by using FileOutputStream & ObjectOutputStream class
class MyBean {
public String firstvalue;
public String secondvalue;
public MyBean (String firstvalue,String secondvalue){
this.firstvalue=firstvalue;
this.secondvalue=secondvalue;
}
}
public class FileSerialization {
public static void main(String[] args) {
try {
MyBean mb = new MyBean("first value", "second value");
// write object to file
FileOutputStream fos = new FileOutputStream("mybean.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(mb);
oos.close();
// read object from file
FileInputStream fis = new FileInputStream("mybean.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
MyBean result = (MyBean) ois.readObject();
ois.close();
System.out.println("One:" + result.firstvalue + ", Two:" + result.secondvalue);
result.firstvalue="Changed;";
// write object to file
fos = new FileOutputStream("mybean.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(result);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Java Cant read or write object to file

There is this method klasOpslaan(Klas deKlas). I need to write deKlas to an object. Afterwards I need to read it with method klasInladen. I am getting an error writing aborted; java.io.NotSerializableException: week5.practicum4.Klas although I implemented Serializeable. I did note that when writing my object it makes the object but doesn't write to it. I did implement everything but StackOverflow wont let me post it.
public class KlasManager implements Serializable {
public void klasOpslaan(Klas deKlas) throws IOException, FileNotFoundException {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("Klas opgeslassgen");
oos.writeObject(deKlas);
oos.close();
}
public Klas klasInladen() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
Klas deKlas = (Klas) ois.readObject();
ois.close();
return deKlas;
}
}
edit: needed Serializeable in other classes, not in this one.

java.io.EOFException when reading an object through ObjectInputStream

Wrote a simple piece of code top serialize standard employee object and deserialize it in the the same machine from different class. Both programs compiled and executed Obj output stream to create serialized object.
Problem is with deserializing it. Program when run gives EOF exception.
Here is the code I am using:
Serialize-
import java.io.*;
public class OOStreamDemo{
public static void main(String []a){
Employee e = new Employee("Abhishek Yadav", 'i', 10014);
FileOutputStream fout = null;
ObjectOutputStream oout = null;
try{
fout = new FileOutputStream("emp.ser");
oout = new ObjectOutputStream(fout);
} catch(Exception ex1){
System.out.println(oout);
ex1.printStackTrace();
}
finally{
try{
oout.flush();
oout.close();
fout.close();
} catch(IOException ex2){
ex2.printStackTrace();
}
}
}
}
Deserialize -
import java.io.*;
public class OIStreamDemo{
public static void main(String []a){
System.out.println("Inside main");
FileInputStream fin = null;
ObjectInputStream oin = null;
Employee emp;
try{
System.out.println("Inside try");
fin = new FileInputStream("emp.ser");
oin = new ObjectInputStream(fin);
System.out.println("Streams Initialized");
while((emp = (Employee)oin.readObject()) != null)
{
System.out.println(emp.toString());
}
System.out.println("Object read");
//System.out.println("Read object is " + emp);
//System.out.println("Obj props are "+ emp.name);
} catch(Exception e){
e.printStackTrace();
}
}
}
This is the printStackTrace:
Inside main
Inside try Streams
Initialized
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2598)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1318)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at OIStreamDemo.main(OIStreamDemo.java:16)
Thank You.
You did not write the Employee object to the ObjectOutputStrem therefore add
oout.writeObject(e);

Serialization in enum

public static void main(String[] args) {
try {
Object input = ABC.ad;
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("test.enum")));
objectOutputStream.writeObject(input);
objectOutputStream.close();
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("test.enum")));
Object outPut = objectInputStream.readObject();
objectInputStream.close();
if(input == outPut) {
System.out.println("Same ............"+input+" "+outPut);
}
} catch (Exception e) {
e.printStackTrace();
}
}
enum ABC {
ad,de;
}
I am trying to serialize enum and deserialize. As expected I got the result "Same". But I dont know how its working. Even I have checked Enum class also. It doesnt have readResovle method like that. Please explain ..

How to save values as an ArrayList of double in file

I want to save values as an ArrayList of double in a file. Whenever there is new value, it should be added in an ArrayList without erasing the previous ones. I'm try to use the function,DataStream. Is it possible? If its possible, please let me know how to implement that.
Please refer below code .
private static String LFILE = "serial";
public static void updateFile(Double num) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try{
List<Double> list = getDoubles();
list.add(num);
fos = new FileOutputStream(LFILE);
oos = new ObjectOutputStream(fos);
oos.writeObject(list);
}catch(Exception e){
e.printStackTrace();
try {
oos.close();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static List<Double> getDoubles() {
FileInputStream fis = null;
ObjectInputStream ois = null;
List<Double> newList = new ArrayList<Double>();
try {
fis = new FileInputStream(LFILE);
ois = new ObjectInputStream(fis);
newList = (ArrayList<Double>) ois.readObject();
} catch (Exception ex) {
try {
fis.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return newList;
}
The class you want to use are ObjectOutputStream and ObjectInputStream
e.g.
http://www.javadb.com/writing-objects-to-file-with-objectoutputstream
http://www.javadb.com/reading-objects-from-file-using-objectinputstream
XStream is a library for Java which supports save/send objects in a xml-format. It is simple to use. XML is human readable making it easy to check its corrent or modify.

Categories