I have following class that implements serialization.
class User implements Serializable{
public User(String username, String password) {
this.username=username;
this.password=password;
}
private static final long serialVersionUID = 1L;
String username;
String password;
}
I try to save the User class object in a text file with following code.Basically I try to write the object and then read it.
public class SerializableExample {
public static void main(String[] args) {
User user = new User("userB","passwordB");
String filename = "E:\\Proj-docs\\userFile.txt";
FileOutputStream file;
try {
file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(user);
out.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
User user2=null;
try {
FileInputStream file2 = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file2);
user2= (User) in.readObject();
Optional checkNull = Optional.ofNullable(user2);
if(checkNull.isPresent()) {
System.out.println(user2.username + " "+user2.password);
}else {
System.out.println("Null Object");
}
}catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
it gives the output userB passwordB
Now let's say I want to change my user object and store it in that same text file
public class SerializableExample {
public static void main(String[] args) {
User user = new User("userD","passwordD");
String filename = "E:\\Proj-docs\\userFile.txt";
FileOutputStream file;
try {
file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(user);
out.close();
file.close();
:
:
:
Now if I read my User object it gives userD passwordD
My question is even after updating my user is there a way I can retrieve the old version of user (one with values userB passwordB) using serialVersionUID ? I want to see how version control can be used in Java serialization when we are updating the object or adding new attributes to our class and not changing serial uid.
Thanks in advance for your input.
Related
So guys i need some help. I have a class Book and i want to save my books object to a Stream and then read this Stream file so i can search my objects from there. I have written my code but it gives me some errors and i can figure out how to print my books values .
So this is my Book class
public class Book {
private Date arr;
private Date depp;
private Type room;
private boolean breakfast = false;
private Person data;
private ObjectOutputStream out;
public Book(String name, String surename, String phone,Date arr, Date depp, Type room, boolean breakfast) {
data = new Person(name,surename,phone);
this.arr = arr;
this.depp = depp;
this.room = room;
this.breakfast = breakfast;
}
public void writeObjToFile(){//here i save my object to stream it gives me error, i call this method after i create my book object to main
try{
out = new ObjectOutputStream(new FileOutputStream("books.txt"));
out.writeObject(this);
}
catch(FileNotFoundException e){
System.err.println("File not Found");
e.printStackTrace();
}catch(IOException e){
System.err.println("IOException");
e.printStackTrace();}
}
}
and this is my Search class :
public class Search {
private FileInputStream fis=null;
private String filename;
public Search(String filename){
this.filename = filename;
File file = new File(filename);
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Book should implement Serializable
Check the API
https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeObject%28java.lang.Object%29
Also, remove the out member from Book class because it's not Serializable either.
I wanna make an ArrayList of objects of my own class named Room and store it to file. I have successfully wrote it but when I read it back to ArrayList it gives me the following error
error: incompatible types
temp_read=filereader.readObject();
^
required: Room
found: Object
My code:
public class Room implements Serializable
{
public String room_number="";
public String teacher_name="";
public String Day_of_class="";
public String class_name="";
public My_Time start_time;
public My_Time end_time;
public Room()
{
room_number="";
teacher_name="";
Day_of_class="";
class_name="";
start_time=new My_Time();
end_time=new My_Time();
}
public Room(String r_name ,String t_name ,String cl,String day,
int hr1,int min1,String am1,int hr2,int min2,String am2 )
{
room_number=r_name;
teacher_name=t_name;
Day_of_class=day;
class_name=cl;
start_time=new My_Time(hr1,min1,am1);
end_time=new My_Time(hr2,min2,am2);
}
public void file_room_writer(/* ArrayList<Room> temp_room ,*/String str )
{
/// file writing handling`enter code here`
//--------------------------------------------------
// Room a1 =temp_room;
try {
File file = new File(str+".txt");
FileOutputStream file_stream=new FileOutputStream(file);
ObjectOutputStream fileWriter = new ObjectOutputStream(file_stream);
fileWriter.writeObject(class_storing);
fileWriter.close();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null,"Exception at file writing ");
}
}
public void file_room_reader(String str )
{
/// file handlingg
//--------------------------------------------------
ArrayList<Room> contain_room ;
try {
File file = new File(str+".txt");
FileInputStream file_stream=new FileInputStream(file);
ObjectInputStream filereader = new ObjectInputStream(file_stream);
temp_read=filereader.readObject();
contain_room=(ArrayList<Room>)filereader.readObject();
filereader.close();
}
catch(Exception e1)
{
e1.getStackTrace();
JOptionPane.showMessageDialog(null,"Exception at file Reading ");
}
}
The readObject method returns an object - you have to try and cast it to a Room.
temp_read = (Room) filereader.readObject();
readObject() returns Object , you'll have to downcast it to the type of temp_read.
Assuming Room is the type of temp_read
temp_read = (Room) filereader.readObject();
This is my first time i try objects serializing.
My problem is that when i call for saving new objects(Reminder.java objects) it saves them in the hash map but when i load it gives me the properties of the last saved object.
So my question is:
1.Saving - How do i "append" objects to a file ?
2.Loading - how to iterate through them and get the right object (using the key class type MyDateClass)
. Example will be welcomed. Thank you.
public void save(MyDateClass chosenDate, String string){
System.out.println("Trying to save");
reminderMap.put(chosenDate, string);
//serializing an object :
this.dateReminder = chosenDate;
this.reminder = string;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/reminder.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/reminder.ser. ");
}catch(IOException i)
{
i.printStackTrace();
}
}
public String Load(MyDateClass chosenDate){
System.out.println("Trying to load");
this.reminder = reminderMap.get(chosenDate);
System.out.println(this.reminder);
// deserialize
Reminder e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/reminder.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Reminder) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
}catch(ClassNotFoundException c)
{
c.printStackTrace();
}
return e.reminder;
}
}
I did a demo and unit test for you, currently I use java.util.Date to substitute your SomeDate class .
update: 2013-12-31
I am not trying to make things complex,but I really feel it is my responsibility to not mislead others,so I try to fixed the code again.Currently, HashMap can't be append,please improve it.Thanks!
this code refactored from your code:
import java.io.*;
import java.util.*;
/**
* refactored by your code
* append object stream haven't realized,please help
* 2013-12-31
*/
public class Reminder implements Serializable {
public static void main(String[] args) {
//do some initialization
Reminder re = new Reminder();
re.put(new Date(System.currentTimeMillis()), "Hope it work!");
re.put(new Date(System.currentTimeMillis()+100), "it work!");
re.put(new Date(System.currentTimeMillis()+200), "Wake up!");
//save to file ,using append mode
String filpath = "/tmp/reminder.ser";
re.save(filpath,true);
//load from file and iterate the key-value pair
Reminder reLoad = Reminder.Load(filpath);
if(reLoad != null) {
Iterator<Map.Entry<Date,String>> it = reLoad.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Date,String> entry = it.next();
System.out.format("reminder: %tc---%s%n",entry.getKey(),entry.getValue());
}
}
}
public Set<Map.Entry<Date,String>> entrySet() {
return reminderMap.entrySet();
}
public void put(Date chosenDate, String string) {
reminderMap.put(chosenDate, string);
}
public String get(Date chosenDate) {
return reminderMap.get(chosenDate);
}
/**
* serializing an object
* #param filePath path to save file
* #param append indicate whether append or not
*/
public void save(String filePath,boolean append){
System.out.println("Trying to save");
try
{
ObjectOutputStream out = new ObjectOutputStream
( new FileOutputStream(filePath,append));
out.writeObject(this);
out.close();
System.out.printf("Serialized data is saved in "+filePath);
}catch(IOException e)
{
e.printStackTrace();
}
}
/**
* deserialize ,load from file and rebuild object
* #param filePath the path from where to load
* #return a new Object
*/
public static Reminder Load(String filePath) {
System.out.println("Trying to load");
Reminder reminder = null;
try
{
ObjectInputStream in = new ObjectInputStream
(new FileInputStream(filePath));
reminder = (Reminder) in.readObject();
in.close();
}catch(IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
return reminder;
}
private static final long serialVersionUID = 1L;
private Map<Date,String> reminderMap = new HashMap<>();
}
I want to print list of data in file
List<TimeSheetVO> timesheetlist;
java.sql.Date dbdateformat = null;
String date="2013-02-06";
timesheetlist=new ArrayList<TimeSheetVO>();
java.sql.Date dbdate=java.sql.Date.valueOf(date);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://192.168.1.101:3306/bio_tracker_eden","eden","centris");
String query = "select * from ai_bio_timesheet where ATTENDANCE_DATE=?";
PreparedStatement psmt=con.prepareStatement(query);
psmt.setDate(1,dbdate );
ResultSet rs=psmt.executeQuery();
while(rs.next())
{
timeSheetVO =new TimeSheetVO();
timeSheetVO.setEMP_ID(rs.getString("EMP_ID"));
timeSheetVO.setATTENDANCE_DATE(rs.getString("ATTENDANCE_DATE"));
timeSheetVO.setIN_TIME(rs.getTime("IN_TIME"));
timeSheetVO.setOUT_TIME(rs.getTime("OUT_TIME"));
timesheetlist.add(timeSheetVO);
File file=new File("D:/timesheet.txt");
ObjectOutputStream outstream=new ObjectOutputStream(new FileOutputStream(file));
outstream.writeObject(timesheetlist);
outstream.flush();
outstream.close();
}
}catch (Exception e) {
e.printStackTrace();
}
Here I retrieve the data from database and store the data into list and that list is stored in to file.
But the file is not stored the values.
Can you explain where the problem is?
Here values are coming from database but not displayed in file
I use the below class:
public class TimeSheetVO implements Serializable{
private String EMP_ID;
private String ATTENDANCE_DATE;
private Time IN_TIME;
private Time OUT_TIME;
private Time TOTAL_HOURS;
public String getEMP_ID() {
return EMP_ID;
}
public void setEMP_ID(String eMP_ID) {
EMP_ID = eMP_ID;
}
public String getATTENDANCE_DATE() {
return ATTENDANCE_DATE;
}
public void setATTENDANCE_DATE(String aTTENDANCE_DATE) {
ATTENDANCE_DATE = aTTENDANCE_DATE;
}
public Time getIN_TIME() {
return IN_TIME;
}
public void setIN_TIME(Time iN_TIME) {
IN_TIME = iN_TIME;
}
public Time getOUT_TIME() {
return OUT_TIME;
}
public void setOUT_TIME(Time oUT_TIME) {
OUT_TIME = oUT_TIME;
}
public Time getTOTAL_HOURS() {
return TOTAL_HOURS;
}
public void setTOTAL_HOURS(Time tOTAL_HOURS) {
TOTAL_HOURS = tOTAL_HOURS;
}
#Override
public String toString() {
return new StringBuffer().append(EMP_ID).
append("\n").
append(ATTENDANCE_DATE).
append("\n").
append(IN_TIME).
append("\n").
append(OUT_TIME).toString();
}
}
Here printing the values in file:
[72013-02-0617:50:1519:19:15
, 132013-02-0619:02:1119:02:25
, 212013-02-0618:25:2218:25:22
, 282013-02-0618:25:4318:25:43
, 442013-02-0619:20:2019:41:21
, 562013-02-0617:54:0817:54:08
]
But I want to print like this:
72013-02-0617:50:1519:19:15
132013-02-0619:02:1119:02:25
212013-02-0618:25:2218:25:22
282013-02-0618:25:4318:25:43
442013-02-0619:20:2019:41:21
562013-02-0617:54:0817:54:08
Here am append \n but new line is not coming
Your serialization works fine, I tested locally, you should be able to re create List of TimeSheetVO by doing deserialization.
Primary purpose of java serialization is to write an object into a
stream, so that it can be transported through a network and that
object can be rebuilt again
If you want write the only content of the object in to file, then you would not require serialization, rather write obj.data as plain text in to file.
--- EDIT--
Can you put serialization code outside while loop?
while(rs.next())
{
timeSheetVO =new TimeSheetVO();
timeSheetVO.setEMP_ID(rs.getString("EMP_ID"));
timeSheetVO.setATTENDANCE_DATE(rs.getString("ATTENDANCE_DATE"));
timeSheetVO.setIN_TIME(rs.getTime("IN_TIME"));
timeSheetVO.setOUT_TIME(rs.getTime("OUT_TIME"));
timesheetlist.add(timeSheetVO);
}
File file=new File("D:/timesheet.txt");
ObjectOutputStream outstream=new ObjectOutputStream(new FileOutputStream(file));
outstream.writeObject(timesheetlist);
outstream.flush();
outstream.close();
This question already has an answer here:
StreamCorruptedException: invalid type code: AC
(1 answer)
Closed 5 years ago.
`I am new to java and getting StreamCorruptedException in the code below... In this code I am trying to read multiple objects from a file using ObjectInputStream... m not able to handle the StreamCorruptedException...the o/p I m getting is
File C098.txt already exists
Product ID:- P001
Description:- Book
Price:- Rs.200
Exception in thread "main" java.io.StreamCorruptedException: invalid type code:
AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1374)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at Utility.getProducts(Utility.java:57)
at Utility.main(Utility.java:23)
CODE:
import java.io.*;
import java.util.*;
class Product implements Serializable{
private static final long serialVersionUID = 1L;
String productId;
String desc;
String price;
public Product(String PId,String a_des,String a_price){
productId=PId;
desc=a_des;
price=a_price;
}
public String toString(){
return "Product ID:- "+productId+"\nDescription:- "+desc+"\nPrice:- "+price;
}
}
class Utility{
// Product objProduct;
public static void main(String args[]) throws Exception{
String cartId = "C098.txt";
Product objProduct = new Product("P001","Book","Rs.200");
addProductToCart(cartId,objProduct);
getProducts(cartId);
objProduct = new Product("P087","Laptop","Rs.45,500");
addProductToCart("C098.txt",objProduct);
getProducts(cartId);
}
public static void addProductToCart(String CId,Product p) throws Exception{
try{
boolean searchFile;
File objFile = new File(CId);
searchFile = objFile.exists();
if(searchFile)
System.out.println("File "+CId+" already exists");
else{
objFile.createNewFile();
System.out.println("File "+CId+" did not exist. It is now created");
}
FileOutputStream objFOS = new FileOutputStream(objFile,true);
ObjectOutputStream objO = new ObjectOutputStream(objFOS);
objO.writeObject(p);
objO.flush();
objO.close();
}catch(Exception e)
{
System.out.println("Exception Caught");
}
}
public static void getProducts(String CId) throws Exception{
Product objProduct1 = new Product("","","");
File objFile1 = new File(CId);
FileInputStream objFIS = new FileInputStream(objFile1);
ObjectInputStream objI = new ObjectInputStream(objFIS);
Object obj = null;
try{
while((obj=objI.readObject()) != null){
if (obj instanceof Product) {
System.out.println(((Product)obj).toString());
}
}
}catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
}finally {
//Close the ObjectInputStream
try{
if (objI != null)
objI.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
}
}`
The problem is because of header issue, You are appending to same file and while returning second object it throws exception because of headers issue. try to write object in different files, you can rid out of the problem.
SCE Thrown when control information that was read from an object stream violates internal consistency checks.
try
import java.io.*;
import java.util.*;
class Product implements Serializable{
private static final long serialVersionUID = 1L;
String productId;
String desc;
String price;
public Product(String PId,String a_des,String a_price){
productId=PId;
desc=a_des;
price=a_price;
}
public String toString(){
return "Product ID:- "+productId+"\nDescription:- "+desc+"\nPrice:- "+price;
}
// Product objProduct;
public static void main(String args[]) throws Exception{
String cartId = "C0982.txt";
Product objProduct = new Product("P001","Book","Rs.200");
addProductToCart(cartId,objProduct);
getProducts(cartId);
Product objProduct1 = new Product("P087","Laptop","Rs.45,500");
addProductToCart("C0981.txt",objProduct1);
getProducts("C0981.txt");
}
public static void addProductToCart(String CId,Product p) throws Exception{
try{
boolean searchFile;
File objFile = new File(CId);
searchFile = objFile.exists();
if(searchFile)
System.out.println("File "+CId+" already exists");
else{
objFile.createNewFile();
System.out.println("File "+CId+" did not exist. It is now created");
}
FileOutputStream objFOS = new FileOutputStream(objFile,true);
ObjectOutputStream objO = new ObjectOutputStream(objFOS);
objO.writeObject(p);
objO.flush();
objO.close();
}catch(Exception e)
{
System.out.println("Exception Caught");
}
}
public static void getProducts(String CId) throws Exception{
Product objProduct1 = new Product("","","");
File objFile1 = new File(CId);
FileInputStream objFIS = new FileInputStream(objFile1);
ObjectInputStream objI = new ObjectInputStream(objFIS);
Object obj = null;
try{
while((obj=objI.readObject()) != null){
if (obj instanceof Product) {
System.out.println(((Product)obj).toString());
}
}
}catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
}finally {
//Close the ObjectInputStream
try{
if (objI != null)
objI.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
</pre>
You can't 'handle' it. You have to prevent it. It results from a design error such as using two ObjectOutputStreams on a stream that is read by a single ObjectInputStream, as you are doing here by appending to the file, or writing data other than objects and not reading it symmetrically.