java.io.EOFException when reading an object through ObjectInputStream - java

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);

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();
}
}
}

Reading after appending objects to serialized file in Java [duplicate]

This question already has answers here:
How to write data with FileOutputStream without losing old data?
(2 answers)
Closed 5 years ago.
I am writing to a stream file in Java. I have read if I want to append I need to override WriteStreamHeader. But even after doing so, I am not able to get free from StreamCorruptedException.
class AppendingObjectOutputStream extends ObjectOutputStream {
public AppendingObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
protected void writeStreamHeader() throws IOException {
reset();
}
}
class Student implements Operations,Serializable
{
private static final long serialVersionUID = 1L;
private int studid;
private String sname;
private int sage;
private long contact;
public Student()
{
studid = 0;
sname = null;
sage = 0;
contact = 0;
}
public void add(Scanner sc)
{
System.out.print("Enter student id: ");
studid = Integer.parseInt(sc.nextLine());
System.out.print("Enter student name: ");
sname = sc.nextLine();
System.out.print("Enter student age: ");
sage = Integer.parseInt(sc.nextLine());
System.out.print("Enter student's contact number: ");
contact=Long.parseLong(sc.nextLine());
}
public void show()
{
System.out.println("Student's details:");
System.out.println("Id no: "+studid);
System.out.println("Name :" + sname);
System.out.println("Age :" + sage);
System.out.println("Contact No. :" + contact);
}
}
class Admin
{
public void addstu(Scanner sc)
{
try
{
Student s = new Student();
s.add(sc);
boolean b = true;
FileInputStream fis = null;
try{
fis = new FileInputStream("student.ser");
fis.close();
}
catch (FileNotFoundException e)
{
b = false;
}
FileOutputStream fos = new FileOutputStream("student.ser");
ObjectOutputStream oos =null;
if(b == true)
{
System.out.println("Appending objects");
oos = new AppendingObjectOutputStream(fos);
}
else
{
System.out.println("Writing objects");
oos = new ObjectOutputStream(fos);
}
oos.writeObject(s);
oos.close();
fos.close();
System.out.println("Student successfully inserted");
fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student result = (Student) ois.readObject();
result.show();
ois.close();
fis.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void displayallstu()
{
try
{
FileInputStream fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("Student's List");
try{
while(true)
{
Student result = (Student) ois.readObject();
result.show();
}
}
catch (EOFException e) {
System.out.println("!!End of file!!");
}
finally{
ois.close();
fis.close();}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
It is called from main and executes properly when addstu() is called for the first time, but when called for next time, displays Successfully Inserted message, but throws exception while reading.
java.io.StreamCorruptedException: invalid stream header: 79737200
What you first generate is:
stream header
student
Then you are overwriting this with:
reset
student
which cannot be read since you’re missing the stream header. You want the following in the file:
stream header
student
reset
student
To get this, you will need to open the output stream in append mode after the file has been created the first time. Since you already have a Boolean indicating if this is necessary, just pass that to the constructor:
FileOutputStream fos = new FileOutputStream("student.ser", b);

Odd output from file

I have an issue with the input I am getting from reading a file.
The file is made in another activity and is very simple:
ArrayList stuff = new ArrayList();
stuff.add("1,2,3");
try{
String saveFile = "saveGamesTest1.csv";
FileOutputStream saveGames = openFileOutput(saveFile, getApplicationContext().MODE_APPEND);
ObjectOutputStream save = new ObjectOutputStream(saveGames);
save.writeObject(stuff);
save.close(); }
In the other activity it's being read via
try {
FileInputStream fileIn=openFileInput("saveGamesTest1.csv");
InputStreamReader InputRead = new InputStreamReader(fileIn);
Scanner s = new Scanner(InputRead).useDelimiter(",");
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
}
I was expecting (and hoping) to get a result back like
1
2
3
However, the result I'm getting is this:
/storage/emulated/0/Android/data/ys.test/files/saveGamesTest1.csv����sr��java.util.ArrayListx����a���I��sizexp������w������t��1
2
3x
What am I doing wrong?
.
EDIT
I tried Serializable as suggested below, like follow:
public class Save implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
}
public void save(){
Save e = new Save();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
String saveFile = "save.ser";
FileOutputStream saveGames = openFileOutput(saveFile, getApplicationContext().MODE_APPEND);
ObjectOutputStream out = new ObjectOutputStream(saveGames);
out.writeObject(e);
out.close();
saveGames.close();
System.out.printf("Serialized data is saved in save.csv");
}
catch(IOException i) {
i.printStackTrace();
out.println("Save exception gepakt");
}
}
However, out.writeObject(e); gives an error saying that this isn't Serializable
You are not storing object as csv but as serialize java object you have to read as an object not as a csv file
take a look here https://www.tutorialspoint.com/java/java_serialization.htm
at Serializing an Object part
You have to use
FileInputStream in = null;
ObjectInputStream ois = null;
ArrayList stuff2 = null;
try {
in = openFileInput("saveGamesTest1.csv");
ois = new ObjectInputStream(in);
stuff2 = (ArrayList) ois.readObject();
} catch(IOException e) {...}
catch(ClassNotFoundException c) {...}
finally {
if (ois != null) {
ois.close();
}
if (in != null) {
in.close();
}
}
If you want a csv file you have to build it for instance by iterate over your array and write one by one the value in your file and adding the separator or follow this
How to serialize object to CSV file?
EDIT :
An elegant way in Java 7 to serialize an object (here a list like in your example) and deserialize :
public class Main {
public static void main(String[] args) {
List<Integer> lists = new ArrayList<>();
List<Integer> readList = null;
String filename = "save.dat";
lists.add(1);
lists.add(2);
lists.add(3);
//serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(lists);
} catch (IOException e) {
e.printStackTrace();
}
//don't need to close because ObjectOutputStream implement AutoCloseable interface
//deserialize
try (ObjectInputStream oos = new ObjectInputStream(new FileInputStream(filename))) {
readList = (List<Integer>) oos.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
//don't need to close because ObjectInputStream implement AutoCloseable interface
//test
if(!lists.equals(readList)) {
System.err.println("error list saved is not the same as the one read");
}
}
}

JAVA Bin IO with Objects

I'm having an issue reading and loading objects to and from a BIN file i keep getting the errors "java.io.WriteAbortedException" and "java.io.NotSerializableException". This is even when my Student object implements Serializable...
LOADER:
try{
FileInputStream fis = new FileInputStream("students.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
while(true){
Student[] stu = null;
int i = 0;
try {
stu = (Student[]) ois.readObject();
studentBag.add(stu[i]);
} catch (EOFException e) {
break;
}
System.out.println(student);
i++;
}
SAVER:
Student[] studentArray = new Student[2];
studentArray[0] = student;
try {
FileOutputStream fos = new FileOutputStream("students.dat", true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentArray);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Nope");
}
Yes I did close the try catches just didnt see a point in putting them here.
Also im getting the errors at this line in the Loder stu = (Student[]) ois.readObject();
and this in the saver studentArray[0] = student;

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 ..

Categories