I need a little bit of help in Java File IO operations. I am trying to append the serialized object to my file but only the last Object is being appended to the file. I have tried many suggestions but no success yet. How I can achieve this, please help?
Here is my Code:
import java.io.BufferedInputStream;
import java.io.File;
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.util.Scanner;
public class Working {
String FILENAME = "E:\\assignment\\userpass\\userpass.txt";
Scanner sc = new Scanner(System.in);
String sUser = null, sPass = null, sRole = null;
Signup signup = new Signup();
public void createUser(){
System.out.println(" Enter username: ");
sUser = sc.next();
System.out.println(" Enter password: ");
sPass = sc.next();
System.out.println(" Enter Role: ");
sRole = sc.next();
Working obj = new Working();
signup.setUsername(sUser);
signup.setPassword(sPass);
signup.setRole(sRole);
obj.serializeUser(signup);
}
public void serializeUser(Signup signup){
FileOutputStream fout = null;
ObjectOutputStream oout= null;
File file = new File(FILENAME);
try{
// fout = new FileOutputStream(file);
// fout = new FileOutputStream(file.getAbsoluteFile(), true);
fout = new FileOutputStream(file, true);
// fout = new FileOutputStream(FILENAME);
oout = new ObjectOutputStream(fout);
oout.writeObject(signup);
System.out.println("User has been serialized");
} catch(Exception e){
e.printStackTrace();
} finally {
if(fout != null){
try{
fout.close();
} catch(IOException e){
e.printStackTrace();
}
}
if(oout != null){
try{
oout.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
}
// for test purpose
public void showUsers(){
Working obj = new Working();
Signup add = obj.deserializeUser(FILENAME);
System.out.println(add);
}
// to show data
//test purpose
public Signup deserializeUser(String filename){
Signup userDetails = null;
File file = new File(FILENAME);
FileInputStream fin = null;
ObjectInputStream oin = null;
try{
fin = new FileInputStream(file);
oin = new ObjectInputStream(fin);
userDetails = (Signup) oin.readObject();
} catch(Exception ex){
ex.printStackTrace();
} finally{
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oin != null) {
try {
oin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return userDetails;
}
}
I have checked here already: 1. http://www.enseignement.polytechnique.fr/informatique/Java/1.8/java/io/FileOutputStream.html#FileOutputStream-java.lang.String-boolean- 2. Appending to an ObjectOutputStream