I'm saving my ArrayList by Serializing it:
public void Save(){
try{
FileOutputStream ficheiro = new FileOutputStream("Gravacao");
ObjectOutputStream out = new ObjectOutputStream(ficheiro);
out.writeObject(ClassListas.ListaCliente);
out.writeObject(ClassListas.ListaFornecedor);
out.writeObject(ClassListas.ListaPessoa);
out.writeObject(ClassListas.ListaStocks);
out.writeObject(ClassListas.ListaVenda);
out.writeObject(ClassListas.ListaRecurso);
out.flush();
out.close();
ficheiro.close();
}catch(IOException e){
e.printStackTrace();
}
}
And I deserialize it by:
public class FormPrincipal extends javax.swing.JFrame {
public FormPrincipal() {
initComponents();
try{
FileInputStream fx = new FileInputStream("Gravacao");
ObjectInputStream in = new ObjectInputStream(fx);
ClassListas.ListaCliente = (ArrayList<ClassCliente>) in.readObject();
ClassListas.ListaFornecedor = (ArrayList<ClassFornecedor>) in.readObject();
ClassListas.ListaPessoa = (ArrayList<ClassPessoa>) in.readObject();
ClassListas.ListaRecurso = (ArrayList<ClassRecurso>) in.readObject();
ClassListas.ListaStocks = (ArrayList<ClassStock>) in.readObject();
ClassListas.ListaVenda = (ArrayList<ClassVenda>) in.readObject();
}catch(Exception e){
e.printStackTrace();
}
}
And this is how i have my ArrayLists declared:
import java.util.ArrayList;
import main.ClassPessoa;
import main.ClassCliente;
import main.ClassFornecedor;
import main.ClassStock;
import main.ClassVenda;
import main.ClassRecurso;
import java.io.Serializable;
/**
*
* #author Skray
*/
public class ClassListas implements Serializable {
//Listas
public static ArrayList<ClassPessoa> ListaPessoa = new ArrayList<ClassPessoa>();
public static ArrayList<ClassCliente> ListaCliente = new ArrayList<ClassCliente>();
public static ArrayList<ClassFornecedor> ListaFornecedor = new ArrayList<ClassFornecedor>();
public static ArrayList<ClassStock> ListaStocks = new ArrayList<ClassStock>();
public static ArrayList<ClassVenda> ListaVenda = new ArrayList<ClassVenda>();
public static ArrayList<ClassRecurso> ListaRecurso = new ArrayList<ClassRecurso>();
}
The problem is, sometimes, when I Deserialize this it won't load to ArrayList, but when I close and open again it Deserializes... Can someone explain me why?
First of all you can write your ClassListas instance instead of reading and writing each and every ArrayList seperately using following line
ClassListas.ListaCliente = (ArrayList<ClassCliente>) in.readObject();
ClassListas.ListaFornecedor = (ArrayList<ClassFornecedor>) in.readObject();
ClassListas.ListaPessoa = (ArrayList<ClassPessoa>) in.readObject();
ClassListas.ListaRecurso = (ArrayList<ClassRecurso>) in.readObject();
ClassListas.ListaStocks = (ArrayList<ClassStock>) in.readObject();
ClassListas.ListaVenda = (ArrayList<ClassVenda>) in.readObject();
out.writeObject(ClassListas.ListaCliente);
out.writeObject(ClassListas.ListaFornecedor);
out.writeObject(ClassListas.ListaPessoa);
out.writeObject(ClassListas.ListaStocks);
out.writeObject(ClassListas.ListaVenda);
out.writeObject(ClassListas.ListaRecurso);
Then the object is loaded from file during component initialisation only you can move code to separate method
public ClassListas readFromFile( String file) {
ClassListas classListas = null ;
try{
FileInputStream fx = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fx);
classListas = (ClassListas) in.readObject();
}catch(Exception e){
e.printStackTrace();
} finally {
if( fx != null )
fx.close();
}
return classListas;
}
public void writeToFile( String file,ClassListas classListas ) {
try{
FileOutputStream ficheiro = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(ficheiro);
out.writeObject(classListas);
out.flush();
out.close();
} catch(IOException e){
e.printStackTrace();
} finally {
if( ficheiro != null )
ficheiro.close();
}
}
You can use call readFromFile and writeToFile in Load and save button of the form.
Related
I'm quite new to java and unsure how to fix this java.io.NotSerializableException error.
I'm trying to use an add button on the GUI to add an object to an array list
Then write that object to a file so I am able to read it back.
Here is the code I'm using for the Branch class which implement Java Serializable:
import java.io.Serializable;
public class Branch implements Serializable{
private String branch_name;
private String branch_address;
public Branch(String Bname, String Baddress) {
this.branch_name = Bname;
this.branch_address = Baddress;
public String getbranch_name(){
return branch_name;
}
public String getbranch_address(){
return branch_address;
}
public void show_branch_details() {
System.out.println( " The branch name is : " + getbranch_name()
+ " branch address :"+ getbranch_address()
}
}
}
Here is the code for the add button:
ArrayList<Branch> BranchList = new ArrayList<Branch>();
JButton AddBranch = new JButton("ADD BRANCH");
AddBranch.setBounds(10, 35, 161, 23);
AddBranch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Bname = branchNameField.getText();
String Baddress = branchAddressField.getText();
Branch A = new Branch(Bname, Baddress);
BranchList.add(A);
for (int i = 0; i < BranchList.size(); i++) {
displayInfo.append(BranchList.get(i).getbranch_name() +);
}
System.out.println("The ArrayList has " + BranchList.size());
for (int i = 0; i < BranchList.size(); i++) {
System.out.println(BranchList.get(i).getbranch_name());
}
try {
FileOutputStream fos = new FileOutputStream("branch.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//oos.writeObject(BranchList);
for (int b = 0; b < BranchList.size(); b++) {
oos.writeObject(BranchList.get(b));
}
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream("branch.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
//BranchList = (ArrayList<Branch>)ois.readObject();
Branch obj = null;
while ((obj = (Branch) ois.readObject()) != null) {
System.out.println("Name:" + obj.getbranch_name() + ", Address:"
+ obj.getbranch_address());
}
ois.close();
} catch (IOException ex) {
System.out.println(" IOE ERROR");
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
System.out.println("class ERROR");
ex.printStackTrace();
}
}
});
Please use this as Branch class :
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
class Branch implements Serializable{
private String branch_name;
private String branch_address;
public Branch(String Bname, String Baddress) {
this.branch_name = Bname;
this.branch_address = Baddress;
}
public String getbranch_name(){
return branch_name;
}
public String getbranch_address(){
return branch_address;
}
public void show_branch_details() {
System.out.println( " The branch name is : " + getbranch_name()
+ " branch address :"+ getbranch_address());
}
}
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Branch A= new Branch("TestA","Add_A");
Branch B= new Branch("TestB","Add_B");
ArrayList<Branch> BranchList = new ArrayList<>();
BranchList.add(A);
BranchList.add(B);
FileOutputStream fos = new FileOutputStream("branch.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(BranchList);
oos.flush();
oos.close();
ArrayList<Branch> OutputBranchList = new ArrayList<>();
FileInputStream fis = new FileInputStream("branch.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
OutputBranchList = (ArrayList) ois.readObject();
for(Branch branch : OutputBranchList) {
System.out.println(branch.getbranch_name()+" "+ branch.getbranch_address());
}
ois.close();
}
}
I need to save an arraylist in a txt when I close a window and load it when I return to open the program so that it shows what is saved in a JTable.
This is my arraylist
ArrayList<Usuarios> Encuestados = new ArrayList<>();
And I'm saving in this way but I would not know how to load the saved txt to the arraylist
public void guardarTxt() throws FileNotFoundException, IOException, ClassNotFoundException{
FileOutputStream fout=new FileOutputStream("Datos/Encuestados.txt");
try (ObjectOutputStream out = new ObjectOutputStream(fout)) {
out.writeObject(Encuestados);
}
}
You just need to serialize and deserialize the objects in the array. You can search for serialize and deserialize objects in java. I have implemented a code below.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
class Usuarios implements Serializable { // will need to implement Serializable class
private static final long serialversionUID = 129348938L; // this is needed
String name;
int age;
// Default constructor
public Usuarios(String name, int age) {
this.name = name;
}
}
public class Main { // Example class for Serialization and deserialization
// method for printing the object
public static void printdata(Usuarios object1) {
System.out.println("name = " + object1.name);
System.out.println("age = " + object1.age);
}
public static void serialize(ArrayList<Usuarios> list, String filename){
// Serialization
try {
// Saving of object in a file
FileOutputStream file = new FileOutputStream
(filename);
ObjectOutputStream out = new ObjectOutputStream
(file);
// Method for serialization of object
out.writeObject(list);
out.close();
file.close();
System.out.println("Object has been serialized");
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
}
public static ArrayList<Usuarios> deserialize(String filename){
// Deserialization
try {
// Reading the object from a file
FileInputStream file = new FileInputStream
(filename);
ObjectInputStream in = new ObjectInputStream
(file);
// Method for deserialization of object
ArrayList<Usuarios> list = (ArrayList<Usuarios>)in.readObject();
System.out.println("Object has been deserialized");
in.close();
file.close();
return list;
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" +
" is caught");
}
return null;
}
public static void main(String[] args) {
Usuarios object1 = new Usuarios ("ab", 20);
Usuarios object2 = new Usuarios ("cd", 21);
String filename = "s.txt";
ArrayList<Usuarios> EncuestadosBeforeSerialization = new ArrayList<>();
EncuestadosBeforeSerialization.add(object1);
EncuestadosBeforeSerialization.add(object2);
System.out.println("Data before Deserialization.");
for (Usuarios object: EncuestadosBeforeSerialization) {
printdata(object);
};
serialize(EncuestadosBeforeSerialization, filename);
System.out.println("\n\nData will be Deserialize.");
ArrayList<Usuarios> EncuestadosAfterSerialization = deserialize(filename);
System.out.println("Data after Deserialization.");
for (Usuarios object: EncuestadosAfterSerialization) {
printdata(object);
};
}
}
Result:
Data before Deserialization.
name = ab
age = 0
name = cd
age = 0
Object has been serialized
Data will be Deserialize.
Object has been deserialized
Data after Deserialization.
name = ab
age = 0
name = cd
age = 0
I'm getting a ClassCastException when I deserialize my object from a file. When I check the file the object is there, so I know it's being serialized correctly. For some reason the code breaks when trying to retrieve the object. The idea is to allow the user to check, by date, all the workouts they've recorded in their log. Also, I've tried implementing a comparator, but I kept getting the same error and I'm all out of ideas. Any help would be much appreciated.
Here is the code that is causing the trouble:
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
}
Here is the workoutLog class:
public class WorkoutLog implements Serializable{
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
I'm including the body of the code for context
package com.alejandro;
import com.alejandro.Utilities.SerializationUtil;
import com.alejandro.model.Exercise;
import com.alejandro.model.Workout;
import com.alejandro.model.WorkoutLog;
import com.sun.istack.internal.NotNull;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.TreeMap;
public class Logger {
public static final String COMPLETE_KEY = "COMPLETE";
public static final String INCOMPLETE_KEY = "INCOMPLETE";
public static final String ADD_KEY = "ADD";
public static final String CHECK_KEY = "CHECK";
public static final String EXIT_KEY = "EXIT";
public static void main(String[] args) throws IOException, ClassNotFoundException {
Logger logger = new Logger();
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
File file = new File("workout.txt");
//im going to need to ask if the user wants to add a workout, close the program, or select a workout
String userInput = checkUserIntention();
//the switch statement goes through all the possible user inputs
switch(userInput){
case Logger.ADD_KEY:
printInstructions();
do{
logger.promptForExerciseData(workout);
}while(!checkIfUserIsDone());
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
break;
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
} catch(EOFException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(ClassCastException E){
E.printStackTrace();
}
break;
case Logger.EXIT_KEY:
System.out.println("\nExiting program...");
break;
}
}
//I'm using this method to explain to the user how to use the program
protected static void printInstructions(){
System.out.println("\nWelcome to Mr.Strong!\n");
System.out.println("This program was developed to help powerlifters keep a log of their lifts.\n");
System.out.println("Because of this, the program will only recognize the following lifts:\n");
System.out.println("Squat, Bench, Deadlift, Press.\n");
System.out.println("The program is case-sensitive, make sure the information is entered as stated above.\n");
}
//this method asks the user for information about the lifts stores them in a workout object
//the methods used here are all organized throught the page, its just to keep things cleaner and separate
protected void promptForExerciseData(Workout workout){
Exercise exercise = new Exercise();
askForExerciseIdentity(exercise);
askForNumsRelLifts(exercise);
workout.getExerciseList().add(exercise);
}
//this will check to see if the user is done inputting the exercises he did, if he finished the program ends.
protected static boolean checkIfUserIsDone(){
Scanner scanner = new Scanner(System.in);
boolean isUserDone = false;
System.out.println("\nEnter: 'complete'" + ", if you are done. " +
"If not, enter:'incomplete " + ".\n");
String answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.COMPLETE_KEY)){
isUserDone = true;
} else if(answer.trim().toUpperCase().equals(Logger.INCOMPLETE_KEY)){
isUserDone = false;
} else{
checkIfUserIsDone();
}
return isUserDone;
}
//check if user wants to add, review, or close
protected static String checkUserIntention(){
String answer = "a";
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease choose an option:\n" +
"1-) Add a workout. Enter 'Add'.\n" +
"2-) Check a workout Enter 'Check'.\n" +
"3-) Exit the program. Enter 'Exit'\n");
answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.ADD_KEY) ||
answer.trim().toUpperCase().equals(Logger.CHECK_KEY)||
answer.trim().toUpperCase().equals(Logger.EXIT_KEY)){
return answer.toUpperCase();
}else{
System.out.println("Incorrect input.");
checkUserIntention();
}
return answer;
}
//all of this part is asking for the exercise data
//this is the part that asks for exercise id
protected void askForExerciseIdentity(Exercise exercise){
Scanner scanner = new Scanner(System.in);
do{
System.out.println("\nEnter a lift:\n");
String exerciseIdentity = scanner.nextLine();
if(exerciseIdentity.equals(exercise.SQUAT_KEY)){
exercise.setExerciseIdentity(exercise.SQUAT_KEY);
}else if(exerciseIdentity.equals(exercise.PRESS_KEY)){
exercise.setExerciseIdentity(exercise.PRESS_KEY);
}else if(exerciseIdentity.equals(exercise.BENCH_KEY)){
exercise.setExerciseIdentity(exercise.BENCH_KEY);
}else if(exerciseIdentity.equals(exercise.DEADLIFT_KEY)){
exercise.setExerciseIdentity(exercise.DEADLIFT_KEY);
}else {
exercise.setExerciseIdentity(null);
System.out.println("Please enter a valid exercise.");
}}while(exercise.getExerciseIdentity() == null);
}
//this is the part that aks for numbers
protected void askForNumsRelLifts(Exercise exercise){
exercise.setWeightUsed(askForWeightUsed());
exercise.setNumOfReps(askForNumOfReps());
exercise.setNumOfSets(askForNumOfSets());
}
protected double askForWeightUsed(){
Scanner scanner = new Scanner(System.in);
double weightUsed;
do{
try{
System.out.println("\nEnter weight used:\n");
weightUsed = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
weightUsed = 0;
}
} while(weightUsed == 0);
return weightUsed;
}
protected double askForNumOfSets(){
Scanner scanner = new Scanner(System.in);
double numOfSets;
do{
try{
System.out.println("\nEnter sets done:\n");
numOfSets = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
numOfSets = 0;
}
}while(numOfSets == 0);
return numOfSets;
}
protected double askForNumOfReps(){
Scanner scanner = new Scanner(System.in);
double reps;
do{
try{
System.out.println("\nEnter reps done:\n");
reps = Double.parseDouble(scanner.nextLine());
} catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
reps = 0;
}
}while(reps == 0);
return reps;
}
}
Here is workout included:
public class Workout implements Serializable{
protected ArrayList<Exercise> mExerciseList;
protected Date mDateCreated;
public Workout(){
mExerciseList = new ArrayList<>();
mDateCreated = new Date();
}
public ArrayList<Exercise> getExerciseList(){
return mExerciseList;
}
public String getDate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sdf.format(mDateCreated);
}}
Here is the seralizationutil:
import com.alejandro.model.WorkoutLog;
import java.io.*;
public class SerializationUtil{
public static Object deserialize(File filename) throws IOException, ClassNotFoundException{
FileInputStream fis = new FileInputStream(filename);
Object obj = new Object();
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
while(fis.available()>0){
obj = ois.readObject();
}
ois.close();
return obj;
}
public static void serialize(Object object, File filename) throws IOException{
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.close();
}}
Here is what the compiler gives me:
java.lang.ClassCastException: java.lang.Object cannot be cast to com.alejandro.model.WorkoutLog
at com.alejandro.Logger.main(Logger.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
just try this simple example, i have modified your code extensively
one more thing, I dont know what implementation you have under SerializationUtil so i created my own implementation
My example works without any issue
package week4;
import java.io.Serializable;
import java.util.TreeMap;
public class WorkoutLog implements Serializable {
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
}
package week4;
import java.io.Serializable;
public class Workout implements Serializable {
String date = "2016-01-13";
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
package week4;
import java.io.File;
import java.io.IOException;
public class TestWorkOut {
public static void main(String[] args) throws IOException, ClassNotFoundException {
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
/* I had path to workout.txt as D:\\workout.txt*/
File file = new File("D:\\workout.txt");
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
}
}
package week4;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializationUtil {
public static void serialize(WorkoutLog workoutLog, File filename) {
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(workoutLog);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static WorkoutLog deserialize(File filename) {
FileInputStream fis = null;
ObjectInputStream in = null;
WorkoutLog workout = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
workout = (WorkoutLog) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return workout;
}
}
Output
Workout saved in...workout.txt
Deserializing from:...workout.txt
[2016-01-13]
Serializing data through
try {
FileOutputStream fileOut = new FileOutputStream(
"C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(r);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/reg.ser");
pr.println("Registered Successfully ");
} catch (IOException i) {
i.printStackTrace();
}
and while Deserializing not getting entire file objects only getting single object i.e starting object only .
FileInputStream fileIn = new FileInputStream("C:\\Users\\saikiran\\Documents\\NetBeansProjects\\FTP\\reg.ser");
ObjectInputStream in = null;
while (fileIn.available() != 0) {
in = new ObjectInputStream(fileIn);
while (in != null && in.available() != 0) {
r = (Registration) in.readObject();
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
if (r.u.equals(ur) && r.p.equals(ps)) {
System.out.println("Logged in :" + "User name :" + r.u + "Password " + r.p);
pr.println("Display");
}
}
}
I have created the working sample for you .
My POJO serializable class will be ,
import java.io.Serializable;
public class Pojo implements Serializable{
String name;
String age;
String qualification;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
}
My main class will be,
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class Serialization {
/**
* #param args
*/
public static final String FILENAME = "F:\\test\\cool_file.ser";
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileOutputStream fos = null;
//ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(FILENAME);
//oos = new ObjectOutputStream(fos);
/* for (String s : test.split("\\s+")) {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
}*/
for(int i=0;i<10;i++){
ObjectOutputStream oos = new ObjectOutputStream(fos);
Pojo pojo = new Pojo();
pojo.setName("HumanBeing - "+i);
pojo.setAge("25 - "+i);
pojo.setQualification("B.E - "+i);
oos.writeObject(pojo);
}
} finally {
if (fos != null)
fos.close();
}
List<Object> results = new ArrayList<Object>();
FileInputStream fis = null;
//ObjectInputStream ois = null;
try {
fis = new FileInputStream(FILENAME);
//ois = new ObjectInputStream(fis);
while (true) {
ObjectInputStream ois = new ObjectInputStream(fis);
results.add(ois.readObject());
}
} catch (EOFException ignored) {
// as expected
} finally {
if (fis != null)
fis.close();
}
System.out.println("results = " + results);
for (int i=0; i<results.size()-1; i++) {
System.out.println(((Pojo)results.get(i)).getName()+ " "+((Pojo)results.get(i)).getAge()+ " "+((Pojo)results.get(i)).getQualification());
}
}
}
Hope it helps.
I have used this code to store Object to a file:
try{
FileOutputStream saveFile=new FileOutputStream("SaveObj.sav");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(x);
save.close();
}
catch(Exception exc){
exc.printStackTrace();
}
}
}
How remove the single Object??
How clear the file??
Well, emptying out a file is very easy -- just open it for writing, and close it again:
new FileOutputStream("SaveObj.sav").close();
That will empty it out. If you were trying to erase one object out of many, though, that's a lot more complicated. You'd either have to read in all the objects and write out only the ones you want to keep, or you'd have to keep an index of the file offsets at which each object starts (probably in a separate file.) At that point you'd want to consider using an object database instead.
Ernest is right in that a removal of a particular object from the object-stream is slightly more complicated. He is also right that when you want to empty a file, you can simply open it for writing and close it. But if you want to remove it from the file-system, it is fine to do it using the File object (do not forget to handle the exceptions and return values correctly). The following example may not be perfect, but it should give you a hint on how to achieve your goals with pure Java. Hope this helps...
package test;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
String filename = "object.serialized";
{
List objects = new ArrayList();
objects.add("String1");
objects.add("String2");
objects.add("String3");
writeObjectsToFile(filename, objects);
}
{
List objects = readObjectsFromFile(filename);
objects.remove(1);
writeObjectsToFile(filename, objects);
}
{
List objects = readObjectsFromFile(filename);
for (Object object : objects) {
System.out.println(object);
}
}
emptyFile(filename);
deleteFile(filename);
}
private static void emptyFile(String filename) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(filename);
} finally {
if (os != null) {
os.close();
}
}
}
private static void deleteFile(String filename) {
File f = new File(filename);
if (f.delete()) {
System.out.println(filename + " deleted sucessfully...");
} else {
System.out.println(filename + " deletion failed!");
}
}
private static void writeObjectsToFile(String filename, List objects) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(os);
for (Object object : objects) {
oos.writeObject(object);
}
oos.flush();
} finally {
if (os != null) {
os.close();
}
}
}
private static List readObjectsFromFile(String filename) throws IOException, ClassNotFoundException {
List objects = new ArrayList();
InputStream is = null;
try {
is = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(is);
while (true) {
try {
Object object = ois.readObject();
objects.add(object);
} catch (EOFException ex) {
break;
}
}
} finally {
if (is != null) {
is.close();
}
}
return objects;
}
}
Outputs:
String1
String3
object.serialized deleted sucessfully...
I know there was a long time from this subject, but just to help future coming people, what works for me was to write the object again as a null value:
public static void writeIncidentsObjectsInCache(Object object) throws IOException {
writeObject(INCIDENTS_CACHE, object); }
public static Object readIncidentsObjectFromCache() throws IOException,
ClassNotFoundException {
return readObject(INCIDENTS_CACHE); }
public static void clearIncidents() throws IOException, ClassNotFoundException {
writeIncidentsObjectsInCache(null); }
public static void writeObject(String key, Object object) throws IOException {
FileOutputStream fos = TheAAApp.getApp().openFileOutput(key, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
fos.close();
}
public static Object readObject(String key) throws IOException,
ClassNotFoundException {
FileInputStream fis = TheAAApp.getApp().openFileInput(key);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
return object;
}