Serialization in enum - java

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

Related

Class cast Exception reading a written file of an ArrayList of Show Objects

/**
* A method that writes variables in a file for shows in the program.
*
* #author
* #version (1.2 2022.01.05)
*/
public void writeShowData(String fileName) throws FileNotFoundException{
String showPath = "c:\\Users\\COMPUTER\\bluej files\\projects\\chapter15\\willem\\CinemaReservationSystemFiles\\";
try
{
FileOutputStream fos = new FileOutputStream(showPath+fileName,true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(show);
oos.flush();
oos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* A method that reads variables in a file for shows setup use in the program.
*
* #author
* #version (1.2 2022.01.05)
*/
public void readShowData(String fileName) throws FileNotFoundException {
try
{ FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
List <Show>shows =(List<Show>)ois.readObject();
ois.close();
System.out.println(shows.toString());// for testing
}
catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
the line : List <Show> shows= (List<Show>)ois.readObject(); gives a
ClassCastexception :class Show cannot be cast to class java.util.List
(etc etc....
I tried many things but can't get it working well.
I made the class show and related classes
Serializable and then write it to shows.ser but when it reads it goes wrong.
Who can help me out on this?
I solved your problem as below. Firstly, you need to change your writing method. If a data file does not exist, you need to create a regular (without append) FileOuputStream for stream header otherwise you will get java.io.StreamCorruptedException (ref). FileOutputStream should be created differently for the next additions.
public static void writeShowData(String fileName) {
String showPath = "E:\\path\\";
try {
File file = new File(showPath + fileName);
ObjectOutputStream oos;
if(file.exists()) {
FileOutputStream fos = new FileOutputStream(file.getAbsolutePath(), true); // with reset fos
oos = new ObjectOutputStream(fos) {
protected void writeStreamHeader() throws IOException {
reset();
}
};
} else {
FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); // regular fos
oos = new ObjectOutputStream(fos);
}
oos.writeObject(show);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Secondly, you need to modify your reading method. If your FileInputStream has data, you need to iterate to add your list.
public static void readShowData(String fileName) {
try {
FileInputStream fis = new FileInputStream("E:\\path\\" + fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
List<Show> shows = new ArrayList<>();
while (fis.available() > 0) {
Show s = (Show) ois.readObject();
System.out.println(s.number);
shows.add(s);
}
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
here is my latest version that is working, the new code does leave out a few lines like if(file.exists){file.delete()}.etc... because the used streams doing that automaticly.
i totally overwrite the file(s) with an update method instead of writing one object at a time.
The earlier answers and some testing by myself made me understand how to get it done right for the purposes in my code.
/**
* A method that writes/saves variables of an Arraylist in a file for seatReservations in the program.
*
* #author Willem
* #version (1.6 2022.01.20)
*/
public void overWriteShowData(String fileName1) throws FileNotFoundException {
String seatReservationPath = "c:\\Users\\COMPUTER\\bluej files\\projects\\chapter15\\willem\\CinemaReservationSystemFiles\\";
try
{ File file = new File(seatReservationPath + fileName1);
ObjectOutputStream oos;
FileOutputStream fos = new FileOutputStream(file.getCanonicalPath(),false); // regular fos
oos = new ObjectOutputStream(fos);
oos.writeObject(shows);
oos.flush();
oos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* A method that reads variables in a file for shows setup use in the program.
*
* #author
* #version (1.6 2022.01.20)
*/
public void readShowData(String fileName1) throws IOException, EOFException,ClassNotFoundException{
FileInputStream fis = new FileInputStream(fileName1);
ObjectInputStream ois = new ObjectInputStream(fis);
shows = (List<Show>) ois.readObject();
ois.close();
}
private void updateAllData(String fileName) {
try {
if(fileName.equals("theatres.ser"))
{overWriteTheatreData(fileName);}
if(fileName.equals("seatPlans.ser"))
{overWriteSeatPlanData(fileName);}
if(fileName.equals("shows.ser"))
{overWriteShowData(fileName);}
if(fileName.equals("customers.ser"))
{overWriteCustomerData(fileName);}
if(fileName.equals("seatReservations.ser"))
{overWriteSeatReservationData(fileName);}
} catch (FileNotFoundException fnfe) {
//fnfe.printStackTrace();
CinemaReservationSystemGUI.cannotFindFileMessage(fileName);
}
}

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

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

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