Serilization Operations - java

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

Related

How to implement Version Control in Java Serialization Using Same SerialUid?

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.

How do you create objects of another class from a .csv file?

Im working on a task that requires me to read from a .csv file using stream API, go over each line and construct an object with the lines. The object class is called Planet and is:
public Planet(String name, long inhabitants, boolean stargateAvailable, boolean dhdAvailable, List<String> teamsVisited) {
}
public String getName() {
return name;
}
public long getInhabitants() {
return inhabitants;
}
public boolean isStargateAvailable() {
return stargateAvailable;
}
public boolean isDhdAvailable() {
return dhdAvailable;
}
public List<String> getTeamsVisited() {
return teamsVisited;
}
#Override
public String toString() {
return name;
}
}
So using stream API to go over each of the lines of the .cvs file i need to create objects of class Planet.
I havent made any progress at all because I really am not sure how to use stream API
public class Space {
public List<Planet> csvDataToPlanets(String filePath) {
return null;
}
try the below snippet.
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().skip(1).map(mapToItem).collect(Collectors.toList());
br.close();
For more information check this link
public static void main(String args[]) {
String fileName = "<Your File Path"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(<Method to split the string based with ',' as delimiter and call Constructor using Reflection API>);
} catch (IOException e) {
e.printStackTrace();
}
}

Error while file reading

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

Serializing objects with hashMap

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

Android readObject exception, cannot cast String to ObjectStreamClass

I am working on an android project that loads data remotely, saves it into an array (if the data is new), writes it to disk as a serializeable, then reads it from disk to load an ArrayList.
Sometimes the ArrayList populates with the data, sometimes it doesn't and the program crashes.
I receive a runtime exception stating: java.land.ClassCastException: java.lang.String cannot be cast to java.io.ObjectStreamClass.
Sometimes I also receive a java.io.StreamCorruptedException, and sometimes I receive and EOFException.
Going through the exception tree, it seems to be originating from this call:
personsArray = (ArrayList<Person>) in.readObject();
Now, sometimes the data loads fine without issues, most of the time the program crashes.
Here is the code that saves the data to disk:
public static boolean saveFromRemoteSource(Context c, ArrayList<?> source){
//Save context
context = c;
//Save source to local file
File file = context.getFileStreamPath(PERSONS_FILE);
//Status if successful in saving
boolean savedStatus = false;
try {
if(!file.exists()){
file.createNewFile();
}else{
//file already exists so don't do anything
}
//now load the data into the file
FileOutputStream fos = context.openFileOutput(PERSONS_FILE, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(source);
oos.close();
savedStatus = true;
} catch(IOException e){
e.printStackTrace();
savedStatus = false;
}
return savedStatus;
}
Here is the code that reads the data from disk:
public static boolean loadPersonsArray(Context c){
context = c;
boolean loadStatus = false;
File file = context.getFileStreamPath(PERSONS_FILE);
try{
if(!file.exists()){
file.createNewFile();
}else {
//File is already created, do nothing
}
BufferedReader br = new BufferedReader(new FileReader(file));
if (br.readLine() != null) {
FileInputStream fis = context.openFileInput(PERSONS_FILE);
ObjectInputStream in = new ObjectInputStream(fis);
personsArray = (ArrayList<Person>) in.readObject();
in.close();
fis.close();
loadStatus = true;
}
br.close();
} catch(IOException e){
e.printStackTrace();
Log.d("TAG", "IOException PERSONS_FILE file: " + e);
loadStatus = false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d("TAG", "ClassNotFoundException PERSONS_FILE file classnotfound: " + e);
}
return loadStatus;
}
This is the Person class:
import java.io.Serializable;
public class Person implements Serializable, Comparable<Person>{
//Person class
private static final long serialVersionUID = 1L;
private String personID;
private String personName;
private boolean displayPerson;
//default constructor
public Person(){
super();
}
public Person(String personID,
String personName,
boolean displayPerson){
super();
this.personID = personID;
this.personName = personName;
this.displayPerson = displayPerson;
}
//Accessor Methods
public String getPersonID(){
return personID;
}
public String getPersonName(){
return personName;
}
public boolean getDisplayPerson(){
return displayPerson;
}
//setter methods
public void setPersonID(String personID){
this.personID = personID;
}
public void setPersonName(String personName){
this.personName = personName;
}
public void setDisplayPerson(boolean displayPerson){
this.displayPerson = displayPerson;
}
#Override
public String toString(){
return this.getPersonName().replaceAll("[^A-Za-z0-9]", "") + this.getDisplayPerson();
}
public int compareTo(Person otherPerson) {
if(!(otherPerson instanceof Person)){
throw new ClassCastException("Not a valid Person object!");
}
Person tempPerson = (Person)otherPerson;
if(this.getPersonName().compareToIgnoreCase(tempPerson.getPersonName()) > 0){
return 1;
}else if(this.getPersonName().compareToIgnoreCase(tempPerson.getPersonName()) < 0){
return -1;
}else{
return 0;
}
}
}
Where the data comes from to be written to the file
private void downloadPersons(){
HashMap<String, String> params = new HashMap<String, String>();
Kumulos.call("selectAllPersons", params, new ResponseHandler() {
#Override
public void didCompleteWithResult(Object result) {
ArrayList<Object> personsList = new ArrayList<Object>();
for(Object o : (ArrayList<?>)result){
Person person = new Person();
person.setPersonID(replaceNandT((String) ((HashMap<?,?>) o).get("personID")));
person.setLawName(replaceNandT((String) ((HashMap<?,?>) o).get("personName")));
person.setDisplayLaw(stringToBool((String)((HashMap<?,?>) o).get("displayPerson")));
if(person.getDisplayPerson()==true){
personsList.add(person);
}
}
//Save personsList to a file
if(PersonsLoader.saveFromRemoteSource(context, personsList)){
updateVersionNumber();
isFinished=true;
Log.d("TAG", "PersonsLoader.saveFromRemoteSource(context, personsList) success");
}
}
});
}
So what do you think is happening at this call?
Get rid of both the blocks that test File.exists(), and the File.createNewFile() calls.
Opening the file for output will create it if necessary.
When opening the file for reading, if the file doesn't exist a FileNotFoundException will be thrown. There's no point in creating an empty file to avert this: it just leads to other problems.
And get rid of the BufferedReader and readLine() calls too. They serve no useful purpose. There are no lines in an object output stream.

Categories

Resources